使用 EF 存储库从聚合根删除子对象

发布于 2025-01-02 04:48:01 字数 2028 浏览 0 评论 0原文

我原来的问题是这里

下面是我更新的代码。

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() 时,它会从集合中删除该项目,但会将记录保留在数据库中,这就是我收到错误的原因。

有没有办法从聚合根中删除子对象并保留聚合根?

My original question is here.

Below is my updated code.

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

When the unit of work tries to commit it produces the following error message.

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.

I know that when I use StockTransfer.RemoveItem() that it removes the item from the collection but it keeps the record in the database, which is why I am receiving the error.

Is there a way of removing the child object from an aggregate Root and persisting the aggregate root?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

孤者何惧 2025-01-09 04:48:01

我对不清楚的代码感到抱歉,但我是一个 C# 人员,所以试图在 VB 代码中找到我的方法。您应该在要清除的实体链接上使用 .Clear() 选项。

例子:

公司>>员工

Company.Emplyees.Clear() 删除关系中的所有记录
表。

Im sorry for the unclear code but im a C# guy so trying to find my way in VB Code. You should use the .Clear() option on the entities link which you want to clear.

Example:

Company <> Employees

Company.Emplyees.Clear() removes all the records in the relation
table.

捂风挽笑 2025-01-09 04:48:01

这也是我遇到的一个问题。我不知道纯粹的解决方案,但在保存更改之前我总是必须在 ef 上下文中手动删除它。在您的存储库方法中,您应该检查 ef 上下文中但不在聚合集合中的实体,并将它们从上下文中的 dbset 中删除。

Thats an issue im having too. I dont know the pure solution, but i always have to delete it in the ef context manualy before saving changes. In your repository method for save You should check for entities which are in the ef context but not in aggregates collection and remove them from the dbset on the context.

被翻牌 2025-01-09 04:48:01

您找到好的解决方案了吗?我使用 ParentAttribute 创建了一个解决方案并扩展了 DbContext SaveChanges 或 ValidateEntity。您可以在此处找到我的解决方案。

Did you find a good solution? I have created a solution using a ParentAttribute and extending the DbContext SaveChanges or ValidateEntity. You can find my solution here.

趴在窗边数星星i 2025-01-09 04:48:01

答案可能有点晚了,但是,我的数据上下文中名为 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; }

    ...
}

The answer might be a little late but, this extension method on my data context called DataContext (which inherits from DbContext) worked for me using 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);
}

And the data context class just for completeness.

public class DataContext : DbContext
{
    public DbSet<MyPOCO> POCOs { get; set; }

    ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文