gpt4 book ai didi

asp.net - 使用两个 FK 时无法创建关系

转载 作者:行者123 更新时间:2023-12-01 22:54:46 25 4
gpt4 key购买 nike

我在 ASP.Net Core 应用程序中使用 EF,并尝试将 UserNotification 表关联到我的 >用户表。这些是表结构:

public class User : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }

public virtual UserNotifications { get; set; }
}

public class UserNotifications
{
public int Id { get; set; }

[Key, ForeignKey("User")]
public string UserId { get; set; }
public User User { get; set; }

[Key, ForeignKey("Sender")]
public string SenderId { get; set; }
public virtual User Sender { get; set; }

public string Title { get; set; }
public string Message { get; set; }
}

我所做的是创建一个UserNotificationsForeignKey,我将存储User 收到的所有通知。

在表UserNotifications内,我为UserSender创建了两个FK。本质上,我想存储已收到通知的 UserId 以及收到通知的 UserId已发送通知(Sender)。

OnModelCreating内部,我还定义了以下逻辑:

builder.Entity<UserNotifications>(entity =>
{
entity.HasKey(n => n.Id);
entity.HasOne(u => u.User)
.WithOne(u => u.UserNotifications)
.HasForeignKey<User>(u => u.Id);

entity.HasOne(u => u.Sender)
.WithOne(u => u.UserNotifications)
.HasForeignKey<User>(u => u.Id);
});

当我在控制台中输入以下建筑物时:

add-migration InitialMigration -context MyAppContext

我得到:

Cannot create a relationship between 'User.UserNotifications' and 'UserNotifications.Sender', because there already is a relationship between 'UserNotifications.User' and 'User.UserNotifications'. Navigation properties can only participate in a single relationship.

我是 EntityFramework 的新手,所以我不知道如何解决这个问题,有人可以解释我做错了什么吗?

预先感谢您的帮助。

最佳答案

您描述的模型表示 UserUserNotifications 之间的两个一对多关系(顺便说一句,该实体应命名为UserNotification)实体。每个 EF 关系可以映射到每一侧的 0 或 1 个唯一导航属性。

您在 UserNotifications 中已拥有两个UserSender 引用导航属性(以及相应的 FK)。您需要的是User两个相应的集合导航属性:

public class User : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }

public virtual ICollection<UserNotifications> ReceivedNotifications { get; set; }
public virtual ICollection<UserNotifications> SentNotifications { get; set; }
}

并使用 Fluent API 进行映射:

builder.Entity<UserNotifications>(entity =>
{
entity.HasKey(n => n.Id);

entity.HasOne(n => u.User)
.WithMany(u => u.ReceivedNotifications)
.HasForeignKey(n => u.UserId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);

entity.HasOne(n => n.Sender)
.WithMany(u => u.SentNotifications)
.HasForeignKey(n => n.SenderId)
.IsRequired()
.OnDelete(DeleteBehavior.Restrict);
});

请注意,由于此类模型引入了所谓的多个级联路径,因此您需要关闭至少一个级联删除并手动处理。

关于asp.net - 使用两个 FK 时无法创建关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52898571/

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