Uwaga: używam Entity Framework w wersji 5najskuteczniej obsługi Create, Update, Delete z kodem Entity Framework Pierwszy
Wewnątrz mojego rodzajowego repozytorium, mam Add
, Edit
i Delete
metody jak poniżej :
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);
}
}
}
Czy myślisz, czy te metody są dobrze wdrożone? Zwłaszcza metoda Add
. Czy byłoby lepiej zastosować metodę Add
jak poniżej?
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;
}
czy to przy użyciu Code First? – PositiveGuy
@CoffeeAddict To EF 5.0.0. DB first lub Code first, nie ma znaczenia tutaj, jak sądzę, ponieważ jest to ogólny kod repozytorium. – tugberk
Możesz użyć nowo wydanej biblioteki, która *** automatycznie ustawi stan wszystkich obiektów na wykresie encji ***. Możesz przeczytać [moja odpowiedź na podobne pytanie] (http://stackoverflow.com/questions/5557829/update-row-if-it-exists-else-insert-logic-with-entity-framework/39609020#39609020) . –