如何使Readity实体框架数据上下文

问题描述 投票:99回答:2

我需要向第三方插件公开实体框架数据上下文。目的是允许这些插件仅获取数据,而不是让它们发出插入,更新或删除或任何其他数据库修改命令。因此,我如何只读取数据上下文或实体。

.net entity-framework entity-framework-4 datacontext readonly
2个回答
159
投票

除了与只读用户连接外,还可以对DbContext执行一些其他操作。

public class MyReadOnlyContext : DbContext
{
    // Use ReadOnlyConnectionString from App/Web.config
    public MyContext()
        : base("Name=ReadOnlyConnectionString")
    {
    }

    // Don't expose Add(), Remove(), etc.
    public DbQuery<Customer> Customers
    {
        get
        {
            // Don't track changes to query results
            return Set<Customer>().AsNoTracking();
        }
    }

    public override int SaveChanges()
    {
        // Throw if they try to call this
        throw new InvalidOperationException("This context is read-only.");
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Need this since there is no DbSet<Customer> property
        modelBuilder.Entity<Customer>();
    }
}

10
投票

与接受的答案相反,我认为favor composition over inheritance会更好。然后就不需要保存诸如SaveChanges之类的方法来抛出异常。而且,为什么你首先需要这样的方法呢?你应该设计一个类,使消费者在查看其方法列表时不会被愚弄。公共接口应该与类的实际意图和目标一致,而在接受的答案中,SaveChanges并不意味着Context是只读的。

在我需要具有只读上下文的地方,例如在CQRS模式的Read端,我使用以下实现。除了向其消费者提供查询功能之外,它不提供任何其他功能。

public class ReadOnlyDataContext
{
    private readonly DbContext _dbContext;

    public ReadOnlyDataContext(DbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public IQueryable<TEntity> Set<TEntity>() where TEntity : class
    {
        return _dbContext.Set<TEntity>().AsNoTracking();
    }

    public void Dispose()
    {
        _dbContext.Dispose();
    }
}

通过使用ReadOnlyDataContext,您只能访问DbContext的查询功能。假设您有一个名为Order的实体,那么您将以下面的方式使用ReadOnlyDataContext实例。

readOnlyDataContext.Set<Order>().Where(q=> q.Status==OrderStatus.Delivered).ToArray();
© www.soinside.com 2019 - 2024. All rights reserved.