我原来的问题是here。
以下是我的更新代码。
Public Function StockTransferItemRemove(removeRequest As StockTransferItemRequest) As StockTransferItemResponse Implements IStockTransferService.StockTransferItemRemove
' create your objects
Dim removeResponse = New StockTransferItemResponse
Dim stockTransfer As New StockTransfer
Dim stockTransferItem As New StockTransferItem
Try
' get the aggregate root
stockTransfer = _stockTransferRepository.FindBy(removeRequest.StockTransferID).FirstOrDefault
stockTransfer.RemoveItem(removeRequest.StockTransferItemView.Id)
_stockTransferRepository.Save(stockTransfer)
Dim count As Integer = _uow.WMSCommit()
If (count > 0) Then
' the object was saved succesfully
removeResponse.Success = True
Else
' the object was not saved successfully
removeResponse.BrokenRules.Add(New BusinessRule(String.Empty, String.Empty, Tags.Messages.Commit_Failed))
End If
Catch ex As Exception
' an unexpected error occured
removeResponse.BrokenRules.Add(New BusinessRule(String.Empty, String.Empty, ex.Message))
End Try
Return removeResponse
End Function
当工作单元尝试提交时,会产生以下错误消息。
The operation failed: The relationship could not be changed because one or more of
the foreign-key properties is non-nullable. When a change is made to a relationship,
the related foreign-key property is set to a null value. If the foreign-key does not
support null values, a new relationship must be defined, the foreign-key property must
be assigned another non-null value, or the unrelated object must be deleted.
我知道当我使用StockTransfer.RemoveItem()时,它会从集合中删除该项,但它会将记录保存在数据库中,这就是我收到错误的原因。
有没有办法从聚合Root中删除子对象并持久保存聚合根?
答案 0 :(得分:0)
我很抱歉代码不清楚,但我是一个C#家伙,所以试图找到我的方式在VB代码。您应该在要清除的实体链接上使用.Clear()选项。
示例:
公司<>员工
Company.Emplyees.Clear()删除关系中的所有记录 表
答案 1 :(得分:0)
这也是一个问题。我不知道纯粹的解决方案,但我总是必须在保存更改之前在ef上下文中手动删除它。在用于保存的存储库方法中您应该检查ef上下文中但不在聚合集合中的实体,并从上下文中的dbset中删除它们。
答案 2 :(得分:0)
你找到了一个好的解决方案吗?我使用ParentAttribute创建了一个解决方案,并扩展了DbContext SaveChanges或ValidateEntity。您可以找到我的解决方案here。
答案 3 :(得分:0)
答案可能有点晚了但是,我的数据上下文中的这个扩展方法DataContext
(继承自DbContext)使用EF4.3为我工作。
public static void Delete<TEntity>(this DataContext context, IEnumerable<TEntity> entities) where TEntity : class, new()
{
foreach (var entity in entities)
{
context.Delete(entity);
}
}
public static void Delete<TEntity>(this DataContext context, TEntity entity) where TEntity : class, new()
{
var obj = context.Entry(entity);
if (obj.State == System.Data.EntityState.Detached)
{
context.Set(typeof(TEntity)).Attach(obj.Entity);
}
context.Set(typeof(TEntity)).Remove(obj.Entity);
}
数据上下文类只是为了完整性。
public class DataContext : DbContext
{
public DbSet<MyPOCO> POCOs { get; set; }
...
}