[英]Entity Framework is Failing Migrations
我正在開發一個使用 EF 的 DotNet Core 應用程序。 我有一個正在工作的數據庫,我正在重新配置我的 model 類,以便它們彼此之間具有正確的關系。 我有 4 個表:電影、用戶、評論和流派。 Genre 和 Movie 應該是多對多的關系,Movie 和 Review 必須是一對多的關系,User 和 Review 必須是一對多的關系。 我已將模型配置如下:
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; }
}
在遷移后嘗試更新數據庫時,我收到錯誤“數據庫中已經存在一個名為“流派”的 object”,並且:
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])
);
我曾嘗試刪除 Movie model 中的導航屬性,因為我認為這會引發錯誤。 但是,當 EF 嘗試應用初始遷移並且無法創建 Genre 時,會發生錯誤,因為這是在初始遷移中創建的第一個表。 這很奇怪,因為在此之前我已經成功添加了大約 12 個遷移(並更新了)。 我一直無法在網上找到類似的問題。 為什么我會收到此錯誤? 我的導航屬性是否配置不正確?
您沒有正確配置多對多關系。 通過制作另一個具有 Genre 和 Movie 表的外鍵的中間 model 更好地實現,並且這兩個表需要具有該中間表的 ICollection 作為屬性。
並且對於Movie 和 Review 之間的一對多關系,您需要 Movie 表中的 Review 集合。
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 Class中的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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.