Lưu ý: Tôi đang sử dụng Entity Framework phiên bản 5hiệu quả Hầu hết các xử lý Tạo, Update, Delete với Entity Framework Mã Trước
Bên trong kho lưu trữ chung của tôi, tôi có Add
, Edit
và Delete
phương pháp như sau :
public class EntityRepository<T> : IEntityRepository<T>
where T : class, IEntity, new() {
readonly DbContext _entitiesContext;
public EntityRepository(DbContext entitiesContext) {
if (entitiesContext == null) {
throw new ArgumentNullException("entitiesContext");
}
_entitiesContext = entitiesContext;
}
//...
public virtual void Add(T entity) {
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
if (dbEntityEntry.State != EntityState.Detached) {
dbEntityEntry.State = EntityState.Added;
}
else {
_entitiesContext.Set<T>().Add(entity);
}
}
public virtual void Edit(T entity) {
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
if (dbEntityEntry.State == EntityState.Detached) {
_entitiesContext.Set<T>().Attach(entity);
}
dbEntityEntry.State = EntityState.Modified;
}
public virtual void Delete(T entity) {
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
if (dbEntityEntry.State != EntityState.Detached) {
dbEntityEntry.State = EntityState.Deleted;
}
else {
DbSet dbSet = _entitiesContext.Set<T>();
dbSet.Attach(entity);
dbSet.Remove(entity);
}
}
}
Bạn có nghĩ rằng các phương pháp này được triển khai tốt không? Đặc biệt là phương pháp Add
. Nó sẽ được tốt hơn để thực hiện các phương pháp Add
như dưới đây?
public virtual void Add(T entity) {
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
if (dbEntityEntry.State == EntityState.Detached) {
_entitiesContext.Set<T>().Attach(entity);
}
dbEntityEntry.State = EntityState.Added;
}
là điều này sử dụng Mã đầu tiên? – PositiveGuy
@CoffeeAddict Đó là EF 5.0.0. DB đầu tiên hoặc Mã đầu tiên, nó không quan trọng ở đây tôi đoán vì nó là một mã kho chung. – tugberk
Bạn có thể sử dụng thư viện mới được phát hành sẽ tự động đặt trạng thái của tất cả các thực thể trong biểu đồ tổ chức ***. Bạn có thể đọc [câu trả lời của tôi cho câu hỏi tương tự] (http://stackoverflow.com/questions/5557829/update-row-if-it-exists-else-insert-logic-with-entity-framework/39609020#39609020) . –