本文介绍了通用访问DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ObjectContext 允许对生成的实体进行通用访问。 DbContext 似乎没有这样的支持。使用通用存储库访问EF5具有挑战性。假设我想要一个通用机制来读取任何给定的实体,称之为TEntity:

ObjectContext allows generic access to the generated Entities. DbContext appears to have no such support. Accessing EF5 with a generic repository is challenging. Let's say I want a generic mechanism to read any given entity, call it TEntity:

public class DataRepositoryEF5<T> where T: DbContext
{
    private ObjectContext _context;

    public DataRepositoryEF5(DbContext context)
    {
        _context = ((IObjectContextAdapter)context).ObjectContext;
    }

    public IEnumerable<TEntity> ReadAll<TEntity>() where TEntity : class,new()
    {
        return GetObjectSet<TEntity>().AsEnumerable();
    }

    protected ObjectSet<TEntity> GetObjectSet<TEntity>() where TEntity : class,new()
    {
        ObjectSet<TEntity> result;
        result = _context.CreateObjectSet<TEntity>();
        return result;
    }
}

用法

            var context = new MyContext();
            var repository = new DataRepositoryEF5<MyContext>(context);

            IEnumerable<Document> results = repository.GetAll<Document>();

            foreach (var item in results)
            {
                Console.WriteLine("{0} {1} {2} {3}", item.Description, item.Id, item.Property, item.Whatever);
            }

EF用于生成具有公共基本类型的类 EntityObject 。既然不是这样,我可以有最好的约束是 class ...

EF used to generate classes with a common base type EntityObject. Since that is no longer the case the best constraint I can have is class...

其次,因为那里不等同于 ObjectContext.CreateObjectSet<>()我被迫从 DbSet 转换为对象集

Second, because there is no equivalent of ObjectContext.CreateObjectSet<>() I am forced to cast from DbSet to ObjectSet.

使用此模式,我不需要 DbContext 。没有泛型,我被迫手动编码所有CRUD操作。我错过了什么?如果没有,是否可以告诉EF5生成代码 ObjectContext

With this pattern in place I have no need for DbContext. Without generics I am forced to hand code all CRUD operations. Did I miss something? If not, is it possible to tell EF5 to generate code with ObjectContext instead?

推荐答案

看看这个提示我曾经发布过

无论如何,诀窍是使用 context.Set<> p>

Anyway the trick is by using context.Set<>

public interface IEntity
        {
            int Id { get; set; }
        }

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class, IEntity
    {
        private IDbContext _context;
        public Repository(IDbContext context)
        {
            _context = context;
        }
          private IDbSet<TEntity> DbSet
         {
            get
            {
                return _context.Set<TEntity>();
            }
         }
          public IQueryable<TEntity> GetAll()
          {
             return DbSet.AsQueryable();
          }
        public void Delete(TEntity entity)
        {
             DbSet.Remove(entity);
        }
.....

这篇关于通用访问DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!