请帮我解决一个问题。 我使用Entity Framework来处理datebase。
我的情况: 我有两张桌子需要填写。其中一个必须包含第二个表中的标识符。现在我将数据插入第一个表并进行保存更改。它给了我实体的识别器,我可以在第二个表中插入来自第一个实体的这个识别器的行。
因此,我的上下文有两个保存更改。我认为这是不好的做法。
代码示例:
var registration = new Registration()
{
//fill some properties
};
_registrationEntityService.Insert(registration);
context.SaveChanges();
var profile = new Profile()
{
//fill some properties
profile.RegId = registration.Id
};
_profileEntityService.Insert(profile);
context.SaveChanges();
我如何解决这个问题?谢谢。
答案 0 :(得分:1)
EF假定使用profile.Registration
等导航属性来解决此类问题:
var registration = new Registration()
{
//fill some properties
};
var profile = new Profile()
{
//fill some properties
profile.Registration = registration
};
context.SaveChanges();
确保您生成了所需的导航属性(它通常基于数据库中的外键)。我强烈建议您先阅读任何EF指南http://www.entityframeworktutorial.net/EntityFramework5/add-entity-graph-using-dbcontext.aspx