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();
Ehsan Mirsaeedi Mar 10 '19 at 22:26 2019-03-10 22:26
source share