什么可以是更好的STE实现,我听说DbContext是用EF实现Repo的最简单的方法,我个人利用了EntityState,但是ObjectContext上有任何成员可以为我提供更多的功能。使用回购的CRUD操作?今天我正在使用像这样的GenericRepository:
public class GenericRepository<TEntity> where TEntity : class
{
internal DbContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(DbContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
public virtual IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
{
return dbSet.SqlQuery(query, parameters).ToList();
}
}
我忘了提到我也在使用Unity,因此对Repository的调用就是这样的:
[Dependency]
public IUnityContainer Container { get; set; }
public List<Case> GetAll()
{
using (var context = Container.Resolve<ClaimEntities>())
{
var qry = (from c in context.Cases
select c).ToList();
return qry;
}
}
答案 0 :(得分:4)
自跟踪实体是ObjectContext的特征 - 它们是not supported in DbContext。如果你想要STE,你需要交换到ObjectContext API并使用STEs T4模板生成实体而不是你当前的POCO。