1

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

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);
        }
}

当我通过这样的服务方法调用 Delete

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

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

4

2 回答 2

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

于 2013-05-19T08:51:18.783 回答
1

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

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

RefreshMode 有 2 个可能的值:ClientWins 和 StoreWins。选择什么值取决于您的策略。在这里,我假设您正在实施“Last Record Wins”策略

于 2013-05-19T09:19:57.090 回答