且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

关系处于已删除状态

更新时间:2023-12-05 23:07:10

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

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.