簡體   English   中英

無法確定導航屬性 Entity Framework Core 表示的關系

[英]Unable to determine the relationship represented by navigation property Entity Framework Core

我目前正在為給定的代碼開發一個使用 EntityFrameworkCore 的 Blazor 應用程序:

    public class Movie
{
    public string title { get; set; }
    public string language { get; set; }

    public HashSet<Staff> staffs { get; set; }
    public HashSet<Tag> tags { get; set; }
    public float averageRating { get; set; }
    public string MovieID { get; set; }

    public Movie(string title, string language, string movieID)
    {
        this.title = title;
        this.language = language;
        staffs = new HashSet<Staff>();
        tags = new HashSet<Tag>();
        averageRating = 0;
        this.MovieID = MovieID;
    }
}


    public class Staff
{
    public string fullName { get; set; }
    public HashSet<Movie> isActor { get; set; }
    public HashSet<Movie> isDirector { get; set; }
    public string StaffID { get; set; }

    public Staff(string fullName, string staffID)
    {
        this.fullName = fullName;
        isActor = new HashSet<Movie>();
        isDirector = new HashSet<Movie>();
        this.StaffID = staffID;
    }
}


    public class Tag
{
    public string name { get; set; }
    public HashSet<Movie> movies { get; set; }
    public string TagID { get; set; }

    public Tag(string name, string tagID)
    {
        this.name = name;
        movies = new HashSet<Movie>();
        this.TagID = tagID;
    }
}

我正在使用代碼優先方法。 我需要使用數據庫,首先,我想修復它,所以當我使用 Add-Migration 時出現錯誤:

無法確定“HashSet”類型的導航“Movie.staffs”表示的關系。 手動配置關系,或使用“[NotMapped]”屬性或使用“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略此屬性。

您需要將MovieID屬性(外鍵)添加到Staff class。

工作人員 class 有兩個 collections 的 Movies,所以 Movie class 不知道staffs是演員還是導演。

所以需要在Movie上定義兩個Staff的collections:

    public HashSet<Staff> actors { get; set; }
    public HashSet<Staff> directors { get; set; }

但 EF 不知道actors是否應該與isActorisDirector配對。 來自MSDN

當在兩種類型之間定義了多個導航屬性時(即不止一對相互指向的導航),導航屬性表示的關系是不明確的。 您將需要手動配置它們以解決歧義。

所以你需要手動配對:

modelBuilder
    .Entity<Movie>()
    .HasMany(p => p.actors)
    .WithMany(p => p.isActor);
modelBuilder
    .Entity<Movie>()
    .HasMany(p => p.directors)
    .WithMany(p => p.isDirector);

暫無
暫無

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

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