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:
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. How can I hydrate all related entities in the entity
object.
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. If I put it before the Entry
call, I get an error on the Entry
call saying that an Entry already exists. I've also tried calling Reload
on the entry, which doesn't seem to do anything.
You need to have Entity2
as virtual
:
public virtual Entity2 { get; set; }
EF will auto hydrate that for you.
And if you happen to change the Entity2Id and want to reload the changed entity, you can do so explicitly by saying:
context.Entry(entity).Reference(p => p.Entity2).Load();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.