如何通过实体框架中的导航属性更新实体? [英] How to update entity through navigation properties in entity framework?
问题描述
我有TableA(ID,Name和TableB_ID)和TableB(TableB_ID,Description),它们有1对多的关系。
创建一个上下文,我想更新TableA中的记录,更改其TableB_ID值。
事情是:我不想直接更新tableB_ID的值。我想通过从TableB中指定不同的描述值来更改该记录。
我是否必须写这个或实体框架是否为我做这个?
谢谢
我尝试过:
使用TableA的导航属性更改描述的值不起作用。
Hi,
I have TableA(ID,Name and TableB_ID) and TableB(TableB_ID,Description), which have a 1 to many relationship.
After creating a context, I want to update a record in TableA, changing its TableB_ID value.
The thing is: I don't want to update the value of tableB_ID directly. I want to change that record by specifying a different "Description" value from TableB.
Do I have to write this or does entity framework do this for me?
THanks
What I have tried:
Changing the value of "Description" by using the navigation properties of TableA is not working.
推荐答案
我认为描述是唯一的。因此,您必须自己搜索匹配的描述。它是这样的:
I assume that description is unique. So you'll have to search for a matching description yourself. It is something like this:
var descr = "something";
var tabB = context.TableB.FirstOrDefault(f => f.Description == descr );
if (tabB == null)
{
// Assume TableB_ID is autonumber / identity in database.
var newTabB = new TableB() { Description = descr };
TableA.TableB = newTabB ;
// Not sure if this line is required.
context.TableB.Add(newTabB);
}
else
TableA.TableB = tabB;
context.SaveChanges();
这篇关于如何通过实体框架中的导航属性更新实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!