簡體   English   中英

EF Core 5.0 添加多對多使得一對多無法確定

[英]EF Core 5.0 Adding many-to-many makes one-to-many unable to determine

我想利用 ef core 5.0 中新的多對多功能。 https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

我現有的課程是

public class User : IdentityUser<int>
{
}

public class Notification
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string Message { get; set; }
    public DateTime Created { get; set; }
    public DateTime Updated { get; set; }
    public User Creator { get; set; }
    public User Updater { get; set; }
    public Notification()
    {
    }
}

我想在它們之間添加一個多對多的關系,所以這些類是

public class User : IdentityUser<int>
{
    public ICollection<Notification> Notifications { get; set; }
}

public class Notification
{
    //[...]
    public ICollection<User> Recipients { get; set; }
}

現在dotnet ef migrations add NotificationRecipients導致Unable to determine the relationship represented by navigation 'Notification.Recipients' of type 'ICollection<User>'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'. Unable to determine the relationship represented by navigation 'Notification.Recipients' of type 'ICollection<User>'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

經過一番研究,我發現了[InverseProperty()]注釋,所以我將它添加到 Notification.cs

public class Notification
{
    //[...]
    [InverseProperty("Notifications")]
    public ICollection<User> Recipients { get; set; }
}

多對多現在似乎已解決,但dotnet ef migrations add NotificationRecipients導致Unable to determine the relationship represented by navigation 'Notification.Creator' of type 'User'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'. Unable to determine the relationship represented by navigation 'Notification.Creator' of type 'User'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

是否有任何注釋可以添加到Notification.CreatorNotification.Updater或任何其他方式來定義UserNotification之間的一對多關系?

我正在使用 MSSQL 作為數據庫。

兩個實體之間的多重關系通常不能自動確定,需要配置。 EF Core 中的許多東西(尤其是與關系相關的)只能使用流暢的 API 進行配置。

因此,與其尋找不存在或不直觀的數據注釋,不如簡單地配置所需的關系(至少 - 導航屬性和基數):

modelBuilder.Entity<Notification>(builder =>
{
    builder.HasOne(e => e.Creator).WithMany();
    builder.HasOne(e => e.Updater).WithMany();
    builder.HasMany(e => e.Recipients).WithMany(e => e.Notifications);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM