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

时间:2012-05-03 18:12:56

标签: .net entity-framework entity-framework-4 datacontext readonly

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

1 个答案:

答案 0 :(得分:158)

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