Make sure you have public DbSet<MyMark> MyMarks { get; set; }
in the MyModelContext
class.
Asp.net Seeding db Entity Framework is not working
-
30-07-2022 - |
문제
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
다른 팁
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
제휴하지 않습니다 StackOverflow