[英]Entity framework entry load related entity
Let's say I have the following auto generated entities 假设我有以下自动生成的实体
public class Entity1
{
public int Id { get; set; }
public int Entity2Id { get; set; }
public Entity2 { get; set; }
}
public class Entity2
{
public int Id { get; set; }
}
I have an update method in my MVC application that looks like this: 我的MVC应用程序中有一个更新方法,如下所示:
public ActionResult Edit(Entity1 entity)
{
_db.Entry(entity).State = EntityState.Modified;
_db.SaveChanges();
DoSomething(entity);
}
Currently entity
has the Entity2Id
property set, but not the Entity2
property set. 当前, entity
具有Entity2Id
属性集,但没有Entity2
属性集。 How can I hydrate all related entities in the entity
object. 如何在entity
对象中合并所有相关实体。
I've tried doing 我试着做
_db.Find(entity.ID)
If I put that method right after calling SaveChanges
it retrieves the cached entity which doesn't have Entity2
hydrated. 如果我在调用SaveChanges
之后立即放置该方法,它将检索没有Entity2
的缓存实体。 If I put it before the Entry
call, I get an error on the Entry
call saying that an Entry already exists. 如果我把它的前Entry
电话,我得到了一个错误Entry
电话,说的条目已经存在。 I've also tried calling Reload
on the entry, which doesn't seem to do anything. 我也尝试在条目上调用Reload
,这似乎没有任何作用。
You need to have Entity2
as virtual
: 您需要将Entity2
为virtual
:
public virtual Entity2 { get; set; }
EF will auto hydrate that for you. EF会自动为您补水。
And if you happen to change the Entity2Id and want to reload the changed entity, you can do so explicitly by saying: 并且,如果您碰巧更改了Entity2Id并想重新加载更改后的实体,则可以通过以下方式明确地这样做:
context.Entry(entity).Reference(p => p.Entity2).Load();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.