Entity Framework データコンテキストを読み取り専用にする方法 質問する

Entity Framework データコンテキストを読み取り専用にする方法 質問する

Entity Framework データ コンテキストをサード パーティ プラグインに公開する必要があります。目的は、これらのプラグインがデータのみを取得できるようにし、挿入、更新、削除、またはその他のデータベース変更コマンドを発行できないようにすることです。したがって、データ コンテキストまたはエンティティを読み取り専用にするにはどうすればよいでしょうか。

ベストアンサー1

読み取り専用ユーザーで接続することに加えて、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>();
    }
}

おすすめ記事