关系处于已删除状态 [英] A relationship is in the Deleted state

查看:119
本文介绍了关系处于已删除状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我试图清除一个集合(调用 .Clear )我得到以下异常:

When I am trying to clear a collection (calling .Clear) I get the following exception:


保存不暴露其关系的外键属性的实体时出错。 EntityEntries属性将返回null,因为单个实体不能被识别为异常的源。通过在您的实体类型中暴露外键属性,可以更容易地处理异常处理。有关详细信息,请参阅InnerException。

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.

内部异常是:


来自User_AvailabilityAssociationSet的关系处于已删除状态。给定多重约束,相应的User_Availability_Target也必须在已删除状态。

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删除项目,但我不感觉我的代码会一样干净。有没有办法通过清理收集来完成这个工作?

I've looked at other alternatives such as using the DbSet to remove items, but I don't feel my code will be as clean. Is there a way to accomplish this by clearing the collection?

推荐答案

我知道使其工作的唯一方法将关系定义为识别关系。需要从可用性中将外键引入用户作为模型中的外键...

The only way that I'm aware of to make it work is defining the relationship as an identifying relationship. It would required to introduce the foreign key from Availability to User as a foreign key into your model...

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

...并将其作为主键的一部分:

...and make it part of the primary key:

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

您可以扩展映射以包含这个外键(只是为了明确,不需要因为EF将按照惯例识别它):

You can extend your mapping to include this foreign key (just to be explicit, it isn't required because EF will recognize it by convention):

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

(BTW:您需要从一侧配置关系,不需要同时拥有你的问题中的这些映射。)

(BTW: You need to configure the relationship only from one side. It is not required to have both these mappings in your question.)

现在你可以用 user.Availability.Clear(); 可用性实体将从数据库中删除。

Now you can clear the collection with user.Availability.Clear(); and the Availability entities will be deleted from the database.

这篇关于关系处于已删除状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆