【发布时间】:2019-03-24 17:05:20
【问题描述】:
我在我的ASP.Net Core 应用程序中使用EF,我正在尝试将UserNotification 表关联到我的User 表。这些是表结构:
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; }
}
我所做的是创建UserNotifications 的ForeignKey,我将存储User 收到的所有通知。
在UserNotifications 表中,我为User 和Sender 创建了两个FK。本质上,我想存储已收到通知的User 的Id,以及已发送通知的User 的Id (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);
});
当我在console 中键入以下建筑物时:
add-migration InitialMigration -context MyAppContext
我明白了:
无法在“User.UserNotifications”和“UserNotifications.Sender”之间创建关系,因为“UserNotifications.User”和“User.UserNotifications”之间已经存在关系。导航属性只能参与单个关系。
我是EntityFramework 的新手,所以我不知道如何解决这个问题,有人可以解释我做错了什么吗?
提前感谢您的帮助。
【问题讨论】:
-
什么是
public virtual UserNotifications { get; set; }? -
我认为是一个集合,属性名称是复数,但让我们等待@Rockj 响应
标签: asp.net entity-framework asp.net-core entity-framework-core