如何通过EntityFramework中的DbSet删除

时间:2013-05-19 08:42:59

标签: asp.net-mvc-3 entity-framework

您好我正在尝试为删除操作编写通用存储库,这是我的存储库

public class Repository<T> : IRepository<T> where T : class, IAggregateRoot
    {

        private readonly DbSet<T> _entitySet;
        private readonly StatosContext _statosContext;

  public Repository(StatosContext statosContext)
        {
            _statosContext = statosContext;
            _entitySet = statosContext.Set<T>();
        }

 public void Add(T entity)
        {
            _entitySet.Add(entity);
        }

  public void Delete(T entity)
        {
            _entitySet.Remove(entity);
        }
}

当我通过像这样的服务方法调用删除时

public void RemoveContact(ContactViewModel contactViewModel)
        {
            var categoryView = new ContactViewModel { ContactId = contactViewModel.ContactId };
            var contact = categoryView.ConvertToContactModel();
            _contactRepository.Delete(contact);
            _contactRepository.SaveChanges();
        }

它不起作用,因为它找不到实体 如何在mt Generic repository中编写Delete方法?

2 个答案:

答案 0 :(得分:2)

问题是您的实体尚未附加。

这是我的通用存储库,看看我是如何做到的

    public void RemoveOnSave(T entity)
    {
        try
        {
            var e = m_Context.Entry(entity);
            if (e.State == EntityState.Detached)
            {
                m_Context.Set<T>().Attach(entity);
                e = m_Context.Entry(entity);
            }
            e.State = EntityState.Deleted;
        }
        catch (InvalidOperationException ex)
        {
            throw new RepositoryTrackingException(
                "An attempt was made to delete an entity you are already modifying, this may happen if you are trying to update using the same repository instance in two place", ex);
        }
    }

https://github.com/lukemcgregor/StaticVoid.Repository/blob/master/StaticVoid.Repository.EntityFramework/DbContextRepositoryDataSource.cs

答案 1 :(得分:1)

如果您正在使用断开连接的实体并且您确定该实体未被上下文跟踪(您应该),则可以编写此简单代码。

public void Delete(T entity)
    {
        try
        {
             _entitySet.Attach(entity);
             _entitySet.Remove(entity);
             _statosContext.SaveChanges();
        }
        catch (OptimisticConcurrencyException e)
        {
             _statosContext.Refresh(RefreshMode.ClientWins,entity);
        }
    }

RefreshMode有两个可能的值:ClientWins和StoreWins。选择什么价值取决于您的策略。在这里,我假设您正在实施“最后记录胜利”策略