0
是否有可能获得已知持久对象的引用没有DB往返,就像使用NHibernate使用ISession.Load(id)
一样?在没有数据库调用的情况下获取持久实体引用
是否有可能获得已知持久对象的引用没有DB往返,就像使用NHibernate使用ISession.Load(id)
一样?在没有数据库调用的情况下获取持久实体引用
是的,如果对象已经加载是可能的。在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;
如果它在缓存中? – OrangeDog 2011-02-02 22:43:56
@OrangeDog假设它不是 – 2011-02-02 22:52:59