gpt4 book ai didi

c# - EF代码优先,不能删除外键关系

转载 作者:太空狗 更新时间:2023-10-29 23:46:01 24 4
gpt4 key购买 nike

这里显示了两个模型:

public class Application
{
public string Name { get; set; }
public virtual ICollection<ApplicationTransaction> ApplicationTransactions { get; set; }
}

public class ApplicationTransaction
{
public long ApplicationId { get; set; }
public virtual Application Application { get; set; }
}

我尝试使用以下代码删除 Application 的所有 ApplicationTransaction:

var app = _repository.Get<Application>(i => i.Id == 1);
app.ApplicationTransactions.Clear();
Context.SaveChanges();

但是当上下文去保存更改时,发生错误:

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.

enter image description here

最佳答案

我遇到了完全相同的问题,这是解决方案:

技巧:在设置父子关系时,您必须在子对象上创建一个“复合”键。这样,当您告诉 Parent 删除其 1 个或所有子项时,相关记录实际上将从数据库中删除。

使用 Fluent API 配置组合键:

modelBuilder.Entity<Child>.HasKey(t => new { t.ParentId, t.ChildId });

然后,删除相关的 child :

var parent = _context.Parents.SingleOrDefault(p => p.ParentId == parentId);

var childToRemove = parent.Children.First(); // Change the logic
parent.Children.Remove(childToRemove);

// or, you can delete all children
// parent.Children.Clear();

_context.SaveChanges();

完成!

关于c# - EF代码优先,不能删除外键关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20770310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com