我有一个通知类
public class Notification
{
public int NotificationId { get; set; }
public string NotificationMessage { get; set; }
public DateTime NotificationSentOn { get; set; }
//TODO: not sure how to map this in fluent api
// a Notification can go to many users
public ICollection<ApplicationUser> ReceivingUsers { get; set; }
}
以及ApplicationUser 的扩展
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
IsAuthor = false;
}
public string Firstname { get; set; }
public string Lastname { get; set; }
public Gender Gender { get; set; }
public DateTime? DateOfBirth { get; set; }
public DateTime RegisteredDate { get; set; }
public bool IsAuthor { get; set; }
// foreign key to UserProfile using the string ID from ApplicationUser
public UserProfile MemberProfile { get; set; }
// collection of notifications for this user
public ICollection<Notification> Notifications { get; set; }
}
以下是与ApplicationUser类中的Notifications属性有关的错误
无法确定由"ICollection"类型的导航属性"ApplicationUser.Notifications"表示的关系。手动配置关系,或使用"[NotMapped]"特性或使用"OnModelCreating"中的"EntityTypeBuilder.ignore"忽略此属性。
我认为关系应该是一个多,即一个通知发给多个ApplicationUsers,但我在Entity中的正常模式配置不起作用,我一定在其中一个类中遗漏了什么。
我不知道如何使用流利的API将Notifications集合或外键关系映射到UserProfile(我使用的是使用IEntityTypeConfiguration接口的EntityConfiguration类)
更新根据Camilo的回答,我更新了我的实体配置,以包括NavigationUser表,设置主键如下
public class NotificationUserEntityConfiguration : IEntityTypeConfiguration<NotificationUser>
{
public void Configure(EntityTypeBuilder<NotificationUser> builder)
{
builder.HasKey(u => new { u.ApplicationUserId, u.NotificationId })
.HasName("PK_NotificationUser");
builder.Property(u => u.NotificationId)
.ValueGeneratedNever()
.IsRequired();
builder.Property(u => u.ApplicationUserId)
.ValueGeneratedNever()
.IsRequired();
}
}
这从数据库创建脚本返回了以下内容
它在ApplicationUser表中创建了一个ForeignKey
table.ForeignKey( name: "FK_AspNetUsers_Notifications_NotificationId",
column: x => x.NotificationId,
principalSchema: "MachineryCtx",
principalTable: "Notifications",
principalColumn: "NotificationId",
onDelete: ReferentialAction.Restrict);
和NotificationUsers表中的ForeignKey返回通知
table.ForeignKey( name: "FK_NotificationUser_Notifications_NotificationId",
column: x => x.NotificationId,
principalSchema: "MachineryCtx",
principalTable: "Notifications",
principalColumn: "NotificationId",
onDelete: ReferentialAction.Cascade);
您正试图将多对多关系建模为一对多关系。
你应该有这样的东西:
public class ApplicationUser
{
...
public ICollection<NotificationUser> Notifications { get; set; }
}
public class Notification
{
...
public ICollection<NotificationUser> Users { get; set; }
}
public class NotificationUser
{
public int ApplicationUserId { get; set; }
public int NotificationId { get; set; }
public ApplicationUser User { get; set; }
public Notification Notification { get; set; }
}
上面写着:
- 用户可以有许多通知
- 一个通知可能有许多用户
您可以拥有IDENTITY
主密钥或具有ApplicationUserId,NotificationId
的复合主密钥