从存储库中删除模型(聚合根)时,还必须删除所有关联的聚合。存储库模式:删除聚合根
我挣扎在我的实体框架6实现存储库模式
在我的例子来实现这一点,我想从CustomerRepository
删除Customer
。所有客户的Order
对象也应该被删除。
库(精简):
public interface IRepository<T> where T : DomainEntity
{
void Remove(T item);
}
public class EntityFrameworkRepository<T> : IRepository<T> where T : DomainEntity
{
private readonly DbSet<T> dbSet;
public DbContext context;
public EntityFrameworkRepository(IUnitOfWork unitOfWork)
{
context = entityFrameworkUnitOfWork.context;
dbSet = dbSet = context.Set<T>();
}
public virtual void Remove(T item)
{
DbEntityEntry dbEntityEntry = context.Entry(item);
if (dbEntityEntry.State == EntityState.Detached)
{
dbSet.Attach(item);
}
dbSet.Remove(item);
}
}
public class EntityFrameworkUnitOfWork : IUnitOfWork
{
public readonly DbContext context;
public EntityFrameworkUnitOfWork()
{
this.context = new ReleaseContext();
}
public void Commit()
{
context.SaveChanges();
}
}
ICustomerRepository
和CustomerRepository
(EF实现):
public interface ICustomerRepository : IRepository<Customer>
{
IEnumerable<Customer> GetAllActive();
}
public class CustomerRepository : EntityFrameworkRepository<Customer>, ICustomerRepository
{
public CustomerRepository(IUnitOfWork unitOfWork)
: base(unitOfWork)
{ }
public override void Remove(Order item)
{
item.Orders.Clear();
base.Remove(item);
}
}
客户端代码:
customerRepository.Remove(customer);
unitOfWork.Commit();
抛出异常:
System.InvalidOperationException:操作失败: 关系不能被改变,因为一个或多个 外键的属性是不可为空。当对 关系进行更改时,相关的外键属性将设置为空值。 如果外键不支持空值,则必须定义新的关系 ,必须为外键属性指定另一个非空值,或者必须删除不相关的对象。
我会除了呼吁item.Orders.Clear()
向EF表明,必须删除关联。
*“所有客户的订单对象也应该删除。”*哇!想一想...一个订单因为客户被删除而不复存在?即使是历史订单?应该删除客户更改历史记录吗?在我看来,“秩序”也应该是一个聚合根,至少在一种情况下。 – MattDavey
@MattDavey:对不起,我应该提到这是示例代码。一个坏例子,正如你所指出的那样。 – davenewza
我不相信真正的会更好。硬删除不仅仅是一种DDD方式。 –