سؤال

I want to seed the database with default data but I get an exception thrown.

I added this initialize class in the DAL namespace

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

    }

}

I added this initialiser to app startup

protected void Application_Start()

   {

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

   }

I get the following error while invoking this

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.
هل كانت مفيدة؟

المحلول 2

Make sure you have public DbSet<MyMark> MyMarks { get; set; } in the MyModelContext class.

نصائح أخرى

Use the IDatabaseInitializer<TContext> interface instead since DropCreateDatabaseIfModelChanges only works with Code-First models:

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

Leave the Database.SetInitializer exactly the same. You probably should wrap it in a pre-processor directive to ensure it never ends up in production code.

#if DEBUG
      Database.SetInitializer<MyModelContext>(new MyModelInitialise());
#endif
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top