How to make Entity Framework Data Context Readonly

I need to open the Entity Framework Data Context for third-party plugins. The goal is to allow these plugins to retrieve data only and not allow them to issue inserts, updates or deletes or any other database change commands. Therefore, how can I make a data context or readonly object.

+98
entity-framework readonly entity-framework-4 datacontext
May 03 '12 at 18:12
source share
2 answers

In addition to connecting to a read-only user, there are several other things you can do for your 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>(); } } 
+157
May 03 '12 at 20:38
source share

In contrast to the accepted answer, I believe that it would be better to give preference to composition rather than inheritance . Then there would be no need to store methods like SaveChanges to throw an exception. Moreover, why do you need such methods at all? You must design the class so that its consumer does not cheat when looking at the list of methods. The open interface should be consistent with the actual intentions and goals of the class, while in the accepted answer, the presence of SaveChanges does not mean that Context is read-only.

In places where I need a read-only context, for example, on the read side of the CQRS template, I use the following implementation. It provides nothing but opportunity requests for its consumer.

 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(); } } 

Using ReadOnlyDataContext, you can only access the capabilities of DbContext requests. Suppose you have an entity called Order, then you will use an instance of ReadOnlyDataContext as shown below.

 readOnlyDataContext.Set<Order>().Where(q=> q.Status==OrderStatus.Delivered).ToArray(); 
+5
Mar 10 '19 at 22:26
source share



All Articles