2011-02-02 61 views

回答

1

是的,如果對象已經加載是可能的。在EF未來CTP5的情況下,你可以使用DbSet<T>實例的新Local屬性:

var entity = context.MySet.Local.SingleOrDefault(e => e.Id == id); 

ObjectContext形勢還是比較複雜的情況下 - 你需要EntityKey情況下這是麻煩的獲得與波蘇斯工作時。我的倉庫代碼

部分:

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class, IEntity 
{ 
    private readonly EntitySetBase _entitySet; 
    private readonly string _entitySetName; 

    protected BaseObjectContext Context { get; set; } 
    protected ObjectSet<TEntity> ObjectSet { get; set; } 

    public Repository(BaseObjectContext context) 
    { 
     if (context == null) 
     { 
      throw new ArgumentNullException("context"); 
     } 


     Context = context; 
     ObjectSet = context.CreateObjectSet<TEntity>(); 

     var container = Context.MetadataWorkspace 
      .GetEntityContainer(Context.DefaultContainerName, DataSpace.CSpace); 
     _entitySet = container.BaseEntitySets 
      .Single(es => es.ElementType.Name == typeof (TEntity).Name); 
     _entitySetName = Context.DefaultContainerName + "." + _entitySet.Name; 
    } 

    public virtual IQueryable<TEntity> GetQuery() 
    { 
     return ObjectSet; 
    } 

    public virtual TEntity GetById(long id) 
    { 
     TEntity entity = TryGetLocalEntity(id); 

     if (entity == null) 
     { 
      entity = GetQuery().SingleOrDefault(o => o.Id == id); 
     } 

     return entity; 
    } 

    private TEntity TryGetLocalEntity(long id) 
    { 
     if (_entitySet == null) 
     { 
      return null; 
     } 

     var key = new EntityKey(_entitySetName, "Id", id); 
     ObjectStateEntry entry; 

     if (Context.ObjectStateManager.TryGetObjectStateEntry(key, out entry)) 
     { 
      return (TEntity) entry.Entity; 
     } 

     return null; 
    } 
} 

如果未加載的情況下,你根本無法獲得而無需查詢DB參考。您可以使用虛擬對象創建。

CTP5例如:

var entity = new MyEntity { Id = id }; 
context.MySet.Attach(entity); 

純EF4例如:

var entity = new MyEntity { Id = id }; 
context.Attach(entity); 

或具有代理創建(CTP5例如)虛擬對象:

CTP5例如:

var entity = context.MySet.Create(); 
enity.Id = id; 

純EF4考試ple:

var entity = context.CreateObject<MyEntity>(); 
entity.Id = id; 
相關問題