我对EntityFramework,ASP.NET和MVC 5相对较新。
从这里开始遵循教程http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started
我想通过添加Movie-Actor的一对多关系来扩展它(这是一个演员可以在很多电影中)。
因此我在我的Model文件夹中有这些代码:
Actor.cs
namespace MvcMovie.Models
{
public class Actor
{
public int ActorId { get; set; }
public String FirstName { get; set; }
public String Address { get; set; }
public ICollection<Movie> Movies { get; set; }
}
}
Movie.cs
namespace MvcMovie.Models
{
public class Movie
{
public int ID { get; set; }
[StringLength(60, MinimumLength = 3)]
public string Title { get; set; }
[Display(Name = "Release Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime ReleaseDate { get; set; }
[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[Required]
[StringLength(30)]
public string Genre { get; set; }
[Range(1, 100)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }
[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[StringLength(5)]
public string Rating { get; set; }
public int ActorId { get; set;}
public Actor Actor { get; set; }
}
}
MovieDBContext.cs
namespace MvcMovie.Models
{
public class MovieDBContext : DbContext
{
public DbSet<Actor> Actors { get; set; }
public DbSet<Movie> Movies { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Actor>().HasKey(p => p.ActorId);
modelBuilder.Entity<Actor>().Property(c => c.ActorId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<Movie>().HasKey(m => m.ID);
modelBuilder.Entity<Movie>().Property(m => m.ID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<Movie>().HasRequired(p => p.Actor)
.WithMany(m => m.Movies)
.HasForeignKey(m => m.ActorId);
base.OnModelCreating(modelBuilder);
}
}
}
然后我在包管理器上尝试了以下命令
PM> Add-Migration ActorTable
PM> Update-Database
并收到以下错误: ALTER TABLE语句与FOREIGN KEY约束冲突&#34; FK_dbo.Movies_dbo.Actors_ActorId&#34;。冲突发生在数据库&#34; MOVIES_bd6a468e283a4100b6021adaf9911f7d&#34;,table&#34; dbo.Actors&#34;,column&#39; ActorId&#39;。
我感觉它与我的数据种子有关(在configuration.cs文件中)
protected override void Seed(MvcMovie.Models.MovieDBContext context)
{
context.Movies.AddOrUpdate(i => i.Title,
new Movie
{
Title = "When Harry Met Sally",
ReleaseDate = DateTime.Parse("1989-1-11"),
Genre = "Romantic Comedy",
Rating = "PG",
Price = 7.99M
},
}
有人可以建议我朝正确的方向发展。感谢
ps:我有MovieController及其相应的View设置(来自我在教程中所示的早期步骤)。
除了麦克的回答:
本文还包含有用的帮助,尤其是在添加迁移和更新数据库部分。
答案 0 :(得分:1)
OnModelCreating中的以下行说明,Movie中需要Actor
modelBuilder.Entity<Movie>().HasRequired(p => p.Actor)
.WithMany(m => m.Movies)
.HasForeignKey(m => m.ActorId);
要成功更新数据库,您可以更改种子方法,如下所示:
context.Movies.AddOrUpdate(i => i.Title,
new Movie
{
Title = "When Harry Met Sally",
ReleaseDate = DateTime.Parse("1989-1-11"),
Genre = "Romantic Comedy",
Rating = "PG",
Price = 7.99M,
Actor = new Actor() { FirstName = "Actor1", Address = "Address1"}
});
希望这有帮助。