如何解决配置中的错误.cs代码优先迁移

本文关键字:cs 错误 代码 迁移 何解决 解决 配置 | 更新日期: 2023-09-27 17:56:48

我正在为Package Manager Console的模型更改设置代码优先迁移,从而在Configuration.cs中创建seed方法。 我将代码放在Seed方法中,它在上下文中显示错误。Movies.AddorUpdate(-----

它说:

方法的类型参数 'System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate(System.Data.Entity.IDbSet, 参数 TEntity[])' 无法从用法中推断出来。尝试指定 显式类型参数。

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",
            Price = 7.99M
        },
        new Movie
        {
            Title = "Ghostbusters ",
            ReleaseDate = DateTime.Parse("1984-3-13"),
            Genre = "Comedy",
            Price = 8.99M
        },
        new Movie
        {
            Title = "Ghostbusters 2",
            ReleaseDate = DateTime.Parse("1986-2-23"),
            Genre = "Comedy",
            Price = 9.99M
        }
    );
}

电影.cs

namespace MvcMovie.Models
{
    public class Movie
    {
        public int ID
        {
            get;
            set;
        }
        public string Title 
        {
            get;
            set; 
        }
        [Display(Name="ReleaseDate")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        public DateTime ReleaseDate 
        {
            get;
            set; 
        }
        public string Genre 
        { 
            get;
            set;
        }
        public decimal Price 
        {
            get;
            set;
        }
    }
   public class MovieDbContext : DbContext
   {
       public DbSet<Movie> Movies { get; set; }
   }
}

如何解决配置中的错误.cs代码优先迁移

您看到的错误可能是由于您有多个名为 Movie 的类。我建议你看看你的命名空间和using语句来整理它。但是,如果您无法更改它们,请使用完整的命名空间显式指定类型(我猜在这里使用哪个命名空间,您可能需要"其他"命名空间!

context.Movies.AddOrUpdate(
    i => i.Title,
    new MvcMovie.Models.Movie
      //^^^^^^^^^^^^^^^^^^^^^ Note the full namespace here
    {
        Title = "When Harry Met Sally",
        ReleaseDate = DateTime.Parse("1989-1-11"),
        Genre = "Romantic Comedy",
        Price = 7.99M
    },
    //Snip rest of code
);