无法确定导航属性实体框架核心表示的关系



我目前正在为给定的代码开发一个使用 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]"属性或使用"OnModelCreateing"中的"EntityTypeBuilder.Ignore"忽略此属性。

Staff 类有两个电影集合,因此 Movie 类不知道staffs是演员还是导演。

因此,您需要在电影中定义两个工作人员集合:

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

但是EF不知道actors应该与isActor配对还是isDirector配对。 从 MSDN:

当在两种类型之间定义了多个导航属性(即,不止一对相互指向的导航)时,导航属性表示的关系是不明确的。您将需要手动配置它们以解决歧义。

因此,您需要手动配对这些:

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

您需要将MovieID属性(外键)添加到Staff类中。

最新更新