0

존 파파 (John Papa)가 CodeCamper 튜토리얼을보고 있는데, EFRepository 클래스의 코드를 발견했습니다. DbEntityEntry를 사용하는 이유와 DbEntityEntry.State 속성에 대한 세부 정보를 찾는 이유를 찾기가 어렵다는 것을 알았습니다.DbEntityEntry를 사용하여 엔티티의 상태를 처리하는 방법은 무엇입니까?

EF는 자동으로 분리 된 개체를 그래프에 첨부합니다 엔티티의 상태를 설정하거나 SaveChanges()가 호출 될 때.

이러한 의미는 무엇입니까? 당신이 당신의 실체가 메모리에 모든 시간 머물 WPF 응용 프로그램이있는 경우

public class EFRepository<T> : IRepository<T> where T : class 
{ 
    protected DbContext DbContext { get; set; } 
    protected DbSet<T> DbSet { get; set; } 

    public EFRepository(DbContext dbContext) 
    { 
     if (dbContext == null) 
     { 
      throw new ArgumentNullException("dbContext"); 
     } 
     DbContext = dbContext; 
     DbSet = DbContext.Set<T>(); 
    } 

    public virtual void Add(T entity) 
    { 
     DbEntityEntry dbEntityEntry = DbContext.Entry(entity); 
     if (dbEntityEntry.State != EntityState.Added) 
     { 
      dbEntityEntry.State = EntityState.Added; 
     } 
     else 
     { 
      DbSet.Add(entity); 
     } 
    } 

    public virtual void Update(T entity) 
    { 
     DbEntityEntry dbEntityEntry = DbContext.Entry(entity); 
     if (dbEntityEntry.State == EntityState.Detached) 
     { 
      DbSet.Attach(entity); 
     } 
     dbEntityEntry.State = EntityState.Modified; 
    } 

    public virtual void Delete(T entity) 
    { 
     DbEntityEntry dbEntityEntry = DbContext.Entry(entity); 
     if (dbEntityEntry.State != EntityState.Deleted) 
     { 
      dbEntityEntry.State = EntityState.Deleted; 
     } 
     else 
     { 
      DbSet.Attach(entity); 
      DbSet.Remove(entity); 
     } 
    } 
} 

답변

0

은 그래서 당신은이 작업을 수행 할 수 있습니다 :

var cakeProduct = new Product{ProductName = "Cake"}; 
MyContext.ProductsDbSet.Add(); 
MyContext.SaveChanges(); 

을하고 (얼마 후 여기에

클래스의 모습입니다)

cakeProduct.ProductName = "Chocolate Cake"; 
MyContext.SaveChanges(); 

당신이 ASP 닷넷 MVC 응용 프로그램이있는 경우 0
MyContext.ProductsDbSet.Remove(cakeProduct); 
MyContext.SaveChanges(); 

는하지만 당신은 전화

[HttpPost] 
public ActionResult Edit(Product someProduct){ 
    //someProduct has only just been created in memory 
    var context = new MyContext(); //the Context does not exist yet 
    context.ProductsRepository.Update(someProduct); 
} 
에 응답해야
관련 문제