如何更新实体框架相关实体 [英] How to update related entities in Entity Framework
问题描述
我有一个MVC项目,并使用实体框架code首先与POCO对象数据库。例如:
公共类ClassA的
{
公众诠释?标识{搞定;组;}
公共字符串名称{;组;}
公共虚拟ClassB的B {搞定;组;}
}公共类ClassB的
{
公众诠释? ID为{获取;设置;}
公共字符串描述{获取;设置;}
}
我有创建或编辑模型一个ActionResult。问题是,当我把这个的ActionResult更新模型,而 model.B
已被更改,关系不保存在数据库中。当的ActionResult被调用来创建一个新的对象,它按预期工作。我该如何解决这个问题?
公众的ActionResult保存(ClassA的模型)
{
model.B = GetBFromDb(model.B.Id.Value); 如果(ModelState.IsValid)
{
如果(id.HasValue)
{
context.Entry(模型).STATE = System.Data.EntityState.Modified;
}
其他
{
context.ClassAs.Add(模型);
}
context.SaveChanges();
//重定向到指数等。
}
返回视图(EditForm模型);
}
我解决它通过更改 ClassA的
与外键 ClassB的
,并设置值出价
:
公共类ClassA的
{
公众诠释?标识{搞定;组;}
公共字符串名称{;组;}
公众诠释投标{获取;集;} //外键到B
公共虚拟ClassB的B {搞定;组;}
}
为什么这外键物业做工作,而不是EF的生成的外KY?
I have an MVC project and using Entity Framework Code First and POCO objects for the database. For example:
public class ClassA
{
public int? Id {get; set;}
public string Name { get; set;}
public virtual ClassB B {get; set;}
}
public class ClassB
{
public int? Id {get;set;}
public string Description {get;set;}
}
I have an ActionResult that create or edit a model. The problem is when I call this ActionResult to update the model, and model.B
has been changed, the relation is not saved in the database. When the ActionResult is called to create a new object it works as expected. How do I solve this?
public ActionResult Save(ClassA model)
{
model.B = GetBFromDb(model.B.Id.Value);
if(ModelState.IsValid)
{
if (id.HasValue)
{
context.Entry(model).State = System.Data.EntityState.Modified;
}
else
{
context.ClassAs.Add(model);
}
context.SaveChanges();
// redirect to index etc.
}
return View("EditForm", model);
}
I solved it by changing ClassA
with a foreign key to ClassB
, and setting the value of BId
:
public class ClassA
{
public int? Id {get; set;}
public string Name { get; set;}
public int BId {get;set;} // foreign key to B
public virtual ClassB B {get; set;}
}
Why does this foreign key property does the job instead of the generated foreign ky of EF?
这篇关于如何更新实体框架相关实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!