1

我想用默认数据为数据库播种,但抛出异常。

我在 DAL 命名空间中添加了这个初始化类

public class MyModelInitialise : DropCreateDatabaseIfModelChanges<MyModelContext>

{

    protected override void Seed(MyModelContext context)

    {

        base.Seed(context);



        var MyMarks = new List<MyMark>

        {

         new Mark{ Name="Mark1", Value="250"},

         new Mark{ Name="Mark2", Value="350"},

         new Mark{ Name="Mark3", Value="450"}

        };

        Marks.ForEach(bm => context.Marks.Add(bm));



        context.SaveChanges();

    }

}

我将此初始化程序添加到应用程序启动

protected void Application_Start()

   {

        Database.SetInitializer<MyModelContext>(new MyModelInitialise());

   }

调用它时出现以下错误

Model compatibility cannot be checked because the DbContext instance was not created
using Code First patterns. DbContext instances created from an ObjectContext or using 
an EDMX file cannot be checked for compatibility.
4

2 回答 2

2

请改用IDatabaseInitializer<TContext>界面,因为DropCreateDatabaseIfModelChanges仅适用于 Code-First 模型:

public class MyModelInitialise : IDatabaseInitializer<MyModelContext>
{
  public void InitializeDatabase(MyModelContext context)
  {    
    // Runs everytime so just avoid if the table already has records.
    if (context.Marks.Count() == 0)
    {
      var MyMarks = new List<MyMark>
      {
        new Mark{ Name="Mark1", Value="250"},
        new Mark{ Name="Mark2", Value="350"},
        new Mark{ Name="Mark3", Value="450"}
      };

      Marks.ForEach(bm => context.Marks.Add(bm));
      context.SaveChanges();
    }
  }
}

留下Database.SetInitializer一模一样的。您可能应该将其包装在预处理器指令中,以确保它永远不会出现在生产代码中。

#if DEBUG
      Database.SetInitializer<MyModelContext>(new MyModelInitialise());
#endif
于 2014-05-09T22:01:06.883 回答
1

确保你public DbSet<MyMark> MyMarks { get; set; }MyModelContext课堂上。

于 2013-11-12T08:02:43.120 回答