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

时间:2015-06-17 12:07:55

标签: c# asp.net-mvc entity-framework

我正在为Package Manager Console的模型更改设置代码首次迁移,这会在 seed 中创建Configuration.cs方法。我将代码放在Seed方法中,并在 context.Movies.AddorUpdate(-----

它说 :

  

方法的类型参数   “System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate(System.Data.Entity.IDbSet,   params 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
        }
    );
}

Movie.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; }
   }
}

1 个答案:

答案 0 :(得分:3)

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

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
);