使用Entity Framework DbContext的DbSet,重新加载所有相关对象/导航属性

3

目前我有:

context.Entry(employee).Reload();
context.Entry(employee).Reference(p => p.Manager).Load();
context.Entry(employee).Reference(p => p.Department).Load();

我希望能够不需要逐个指定相关实体而加载它们。类似以下方式会非常理想:
context.Entry(employee).Reload();
context.Entry(employee).LoadAllReferences();

可以做到吗?
1个回答

1
我们遇到了一个类似的问题,即在另一个类中将实体类添加到集合中,但导航属性没有被设置,并且这些内容存储在共享的 DbContext 中。
我们决定从上下文中分离实体,然后重新查询 Db,如果需要重新加载导航属性(例如这些解决方案:强制重新加载 Entity Framework 中插入/添加的实体http://dev-doc.blogspot.co.uk/2015/09/entity-framework-reload-newly-created.html)。
以下是我们使用的代码示例:
   public class EntityRetriever
    {
        private readonly System.Data.Entity.DbContext _context;

        public EntityRetriever(System.Data.Entity.DbContext context)
        {
            _context = context;
        }

        public T RetrieveEntity<T>(params object[] entityKeyValues) where T : class
        {

            var entity = _context.Set<T>().Find(entityKeyValues);
            //check if is not an EF proxy class or has changed
            if (entity != null 
                && !IsProxy(entity)
                &&  _context.Entry(entity).State == System.Data.Entity.EntityState.Unchanged)
            {
                //This is the important part to reload navigation properties:
                //detach entity from context and reload from db
                _context.Entry(entity).State = System.Data.Entity.EntityState.Detached;
                entity = _context.Set<T>().Find(entityKeyValues);
            }
            return entity;
        }

        public static bool IsProxy(object entityObject)
        {
            return entityObject != null &&
                System.Data.Entity.Core.Objects
                    .ObjectContext.GetObjectType(entityObject.GetType()) != entityObject.GetType();
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接