gpt4 book ai didi

c# - 关系处于已删除状态

转载 作者:IT王子 更新时间:2023-10-29 04:14:44 34 4
gpt4 key购买 nike

当我尝试清除集合(调用 .Clear)时,出现以下异常:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

内部异常是:

A relationship from the 'User_Availability' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'User_Availability_Target' must also in the 'Deleted' state.

用户看起来像这样:

....
ICollection<Availability> Availability { get; set; }

可用性如下所示:

int ID { get; set; }
User User { get; set; }
DateTime Start { get; set;
DateTime End { get; set; }

配置如下:

HasMany(x => x.Availability).WithRequired(x => x.User);
HasRequired(x => x.User).WithMany(x => x.Availability);

导致问题的代码是:

user.Availability.Clear();

我已经研究过其他替代方法,例如使用 DbSet 删除项目,但我觉得我的代码不会那么干净。有没有办法通过清除集合来实现这一点?

最佳答案

我知道让它起作用的唯一方法是将关系定义为 identifying relationship .需要将外键从 Availability 引入到 User 作为模型的外键...

public int ID { get; set; }
public int UserID { get; set; }
public User User { get; set; }

...并使其成为主键的一部分:

modelBuilder.Entity<Availability>()
.HasKey(a => new { a.ID, a.UserID });

您可以扩展您的映射以包含此外键(明确地说,它不是必需的,因为 EF 会按照惯例识别它):

modelBuilder.Entity<Availability>()
.HasRequired(a => a.User)
.WithMany(u => u.Availability)
.HasForeignKey(a => a.UserID);

(顺便说一句:您只需要从一侧配置关系。您的问题中不需要同时拥有这两个映射。)

现在您可以使用 user.Availability.Clear(); 清除集合,Availability 实体将从数据库中删除。

关于c# - 关系处于已删除状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17850702/

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