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
'programing tip' 카테고리의 다른 글
주요 SQL 데이터베이스에서 CREATE TABLE 및 ALTER TABLE 문을 롤백 할 수 있습니까? (0) | 2020.08.15 |
---|---|
모호한 일치 예외 방지 (0) | 2020.08.15 |
자바에서지도의 얕은 사본 (0) | 2020.08.15 |
allowDefinition = 'MachineToApplication'VS2010에서 게시 할 때 오류 발생 (이전 빌드 이후에만) (0) | 2020.08.15 |
개체 참조가 개체의 인스턴스로 설정되지 않았습니다. .NET에서 어떤 개체가 'null'인지 표시하지 않는 이유는 무엇입니까? (0) | 2020.08.15 |