实体框架迁移失败



我正在开发一个使用EF的DotNet Core应用程序。我有一个数据库在工作,我正在重新配置我的模型类,以便它们之间有正确的关系。我有4张表:电影,用户,评论和流派。流派和电影应该有多对多的关系,电影和评论必须是一对多的,用户必须和评论有一对多关系。我配置的模型如下:

public class Movie
{
[Key]
public int MovieId { get; set; }
[Required]
public string imdbId { get; set; }
public string title { get; set; }
public virtual ICollection<Genre> Genres { get; set; }
}
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
}
public class Review
{
[Key]
public int ReviewId { get; set; }
public int goreRating { get; set; }
public int shockRating { get; set; }
public int jumpRating { get; set; }
public int plotRating { get; set; }
public int supernaturalRating { get; set; }
public int starRating { get; set; }
public int MovieId { get; set; }
public User User { get; set; }
public virtual Movie Movie { get; set; }    
}
public class Genre
{
public int GenreId { get; set; }
//Navigational Properties
public virtual ICollection<Movie> Movies { get; set; }
}

当试图在迁移后更新数据库时,我得到错误"数据库中已经有一个名为"Genres"的对象">,这是:

Applying migration '20210514094730_initial'.
Failed executing DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Genres] (
[Id] int NOT NULL IDENTITY,
CONSTRAINT [PK_Genres] PRIMARY KEY ([Id])
);

我已经尝试删除电影模型中的导航属性,因为我认为这会引发错误。然而,错误发生在EF试图应用初始迁移,但未能创建Genre时,因为这是在初始迁移中创建的第一个表。这很奇怪,因为在此之前我已经成功地添加了大约12个迁移(并进行了更新(。我在网上找不到类似的问题。为什么我会出现此错误?我的导航属性是否配置错误?

您没有正确配置多对多关系。最好通过制作另一个具有Genre表和Movie表的外键的中间模型来实现,并且这两个表需要将该中间表的ICollection作为属性。

此外,对于电影和评论之间的一对多关系,您需要电影中评论表的集合。

public class Movie
{
[Key]
public int MovieId { get; set; }
[Required]
public string imdbId { get; set; }
public string title { get; set; }
public ICollection<MovieGenre> MovieGenres { get; set; }
public ICollection<Review> Reviews { get; set; }
}

public class Genre
{
[Key] 
public int GenreId { get; set; }
public ICollection<MovieGenre> MovieGenres { get; set; }
}

public class MovieGenre
{
public int MovieId{ get; set; }
public Movie Movie{ get; set; }
public int GenreId{ get; set; }
public Genre Genre{ get; set; }
}

用于多对多关系的另一件事是DbContext类中的FluentApi,以成功实现关系。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MovieGenre>()
.HasKey(bc => new { bc.Movie, bc.Genre });  
//for relation between movie and moviegenre
modelBuilder.Entity<MovieGenre>()
.HasOne(bc => bc.Movie)
.WithMany(b => b.MovieGenres)
.HasForeignKey(bc => bc.MovieId);  
//for relation between genre and moviegenre
modelBuilder.Entity<MovieGenre>()
.HasOne(bc => bc.Genre)
.WithMany(c => c.MovieGenres)
.HasForeignKey(bc => bc.GenreId);
}

最新更新