programing tip

Entity Framework 데이터 컨텍스트를 읽기 전용으로 만드는 방법

itbloger 2020. 8. 15. 08:51
반응형

Entity Framework 데이터 컨텍스트를 읽기 전용으로 만드는 방법


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

받아 들여지는 대답과 달리 상속 보다 구성을 선호하는 것이 더 낫다고 생각합니다 . 그러면 예외를 발생시키기 위해 SaveChanges와 같은 메서드를 유지할 필요가 없습니다. 더군다나 애초에 그러한 방법이 필요한 이유는 무엇입니까? 소비자가 메서드 목록을 볼 때 속지 않는 방식으로 클래스를 디자인해야합니다. 공용 인터페이스는 클래스의 실제 의도 및 목표와 일치해야하며 허용 된 답변에서 SaveChanges가 있다고해서 Context가 읽기 전용임을 의미하지는 않습니다.

CQRS 패턴 의 읽기 쪽과 같이 읽기 전용 컨텍스트가 필요한 곳에서는 다음 구현을 사용합니다. 소비자에게 쿼리 기능 외에는 아무것도 제공하지 않습니다.

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

By using ReadOnlyDataContext, you can have access to only querying capabilities of DbContext. Let's say you have an entity named Order, then you would use ReadOnlyDataContext instance in a way like below.

readOnlyDataContext.Set<Order>().Where(q=> q.Status==OrderStatus.Delivered).ToArray();

참고URL : https://stackoverflow.com/questions/10437058/how-to-make-entity-framework-data-context-readonly

반응형