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

最佳答案

除了与只读用户建立连接外,您还可以对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>();
    }
}

07-28 02:12
查看更多