【问题标题】:What is the equivalent of DbSet<TEntity>.Local in the ObjectSet<TEntity>?ObjectSet<TEntity> 中的 DbSet<TEntity>.Local 等价物是什么?
【发布时间】:2013-06-26 19:53:14
【问题描述】:

我正在尝试获取已加载到上下文中的实体。这是一个遗留系统,因此我无法更改上下文创建(以便我可以通过 DbSet 访问它)并且必须通过 ObjectSet API 工作。

ObjectSet API 中 DbSet.Local 属性的最佳等效项是什么?

看起来我可以使用 objectContext.GetObjectByKey(key)objectContext.ObjectStateManager.GetObjectStateEntry(key) 之类的东西,但 EntityKey 的创建似乎涉及将类型和属性名称硬编码为字符串:

var key = new EntityKey("MyEntities.Employees", "EmployeeID", 1);

有没有更好的办法?

【问题讨论】:

  • DbSet.Local 下查看here
  • 谢谢,这很有帮助。看了看她的书。看起来像 GetObjectStateEntries。
  • 也许把它作为答案发布呢?

标签: entity-framework


【解决方案1】:

或以上作为扩展方法:

public static IEnumerable<T> Local<T>(this ObjectSet<T> ObjectSet) where T : class
{
   var localObjects = ObjectSet.Context.ObjectStateManager
       .GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Unchanged)
       .Where(e => e.Entity is T)
       .Select(e => e.Entity as T);
   return localObjects;
}

用法:

Row row = Context.MyObjectSet.Where(mos => mos.Key == key).FirstOrDefault();

if (row == null) // no row exists
{
    // see if the row exists in the Entity Cache
    row = Context.MyObjectSet.Local<MyObjectType>().Where(mos => mos.Key == key).FirstOrDefault();

    if (row == null)
    {
        row = new MyObjectType();  // no, so create a new one
        Context.MyObjectSet.AddObject(row);
    }
}

【讨论】:

    【解决方案2】:

    根据 Gert 和她的书(“Programming Entity Framework”)链接的 Julie Lerman 的博客文章,看来我要使用这个辅助方法:

    public class MyUnitOfWork : MyEntities 
    {
        public IEnumerable<T> GetLocalObjects<T>() where T : class
        {
            var localObjects = ObjectStateManager
                .GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Unchanged)
                .Where(e => e.Entity is T)
                .Select(e => e.Entity as T);
            return localObjects;
        }
    }
    

    然后按如下方式使用:

    _myUnitOfWork.GetLocalObjects<Employee>().First(x => x.EmployeeID == 1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 2011-11-17
      相关资源
      最近更新 更多