ApplicationDbContext和DbContext有什么区别

时间:2018-10-23 08:30:22

标签: c# entity-framework repository-pattern

我正在网上寻找如何使用EF创建动态存储库,而且我经常看到人们将ApplicationDbContext用作私有对象。

我猜它是从DbContext派生的,但是仅使用DbContext是否有任何问题?

顺便说一句,我似乎无法添加ApplicationDbContext ..我缺少任何使用吗?

public class Repository<T> : IRepository<T> where T : EntityBase
{
    private readonly ApplicationDbContext _dbContext;

    public Repository(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public virtual T GetById(int id)
    {
        return _dbContext.Set<T>().Find(id);
    }

    public virtual IEnumerable<T> List()
    {
        return _dbContext.Set<T>().AsEnumerable();
    }

    public virtual IEnumerable<T> List(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {
        return _dbContext.Set<T>()
               .Where(predicate)
               .AsEnumerable();
    }

    public void Insert(T entity)
    {
        _dbContext.Set<T>().Add(entity);
        _dbContext.SaveChanges();
    }

    public void Update(T entity)
    {
        _dbContext.Entry(entity).State = EntityState.Modified;
        _dbContext.SaveChanges();
    }

    public void Delete(T entity)
    {
        _dbContext.Set<T>().Remove(entity);
        _dbContext.SaveChanges();
    }
}

1 个答案:

答案 0 :(得分:1)

带支架的ApplicationDbContext可以从IdentityDbContext继承,或者两个都可以从具有EntityFramework功能的DbContext继承。换句话说,ApplicationDbContext可能具有您的上下文,它正在合并您的上下文,是的,您可以使用自己的DbContext。