簡體   English   中英

實體框架播種未創建數據

[英]Entity Framework Seeding is not creating data

我可以成功執行EF遷移。 可以創建我的表,但是沒有種子數據。 我嘗試了一些方法為Entity Framework 6播種數據,但無濟於事。

public class EmployeeDBContextSeeder :
       DropCreateDatabaseIfModelChanges<EmployeeDBContext>
{
    protected override void Seed(EmployeeDBContext context)
    {
        List<Employee> EmployeeList = new List<Employee>()
        {
            new Employee() { FirstName = "Mark" },
            new Employee() { FirstName = "Ben" },
            new Employee() { FirstName = "John" }
        };

        context.Employees.AddRange(EmployeeList);
        context.SaveChanges();
        //  base.Seed(context);
    }
}

public class EmployeeDBContext : DbContext
{
    public EmployeeDBContext() : base("DB")
    {
        Database.SetInitializer<EmployeeDBContext>(new EmployeeDBContextSeeder());
    }

    public DbSet<Employee> Employees { get; set; }
}

而且我不確定這兩個context.SaveChanges();之間有什么區別context.SaveChanges(); vs base.Seed(context);

我試圖移動Database.SetInitializer<EmployeeDBContext>(new EmployeeDBContextSeeder()); 到global.asax Application_Start(),但仍無法將數據播種到我的表中。

對於遷移命令,我使用enable-migrationsAdd-Migration InitialUpdate-database

我正在這樣設置初始化程序:在您的DbContext

public static void Initialize()
{
   Database.SetInitializer( new MigrateDatabaseToLatestVersion<MyContext, MyConfiguration>() );
}

在migrations文件夾中有配置類:

public sealed class MyConfiguration : 
   DbMigrationsConfiguration<MyContext>
{
   public Configuration()
   {
      AutomaticMigrationsEnabled = true;
   }

   protected override void Seed( MyContext context )
   {
      //insert statements here
   }
}

它有效:-)

我認為您無需對base.Seed(context)進行base.Seed(context)

請執行下列操作

public class SchoolDBInitializer : DropCreateDatabaseAlways<SchoolDBContext>
 {
  protected override void Seed(SchoolDBContext context)
  {
      IList<Standard> defaultStandards = new List<Standard>();

    defaultStandards.Add(new Standard() { StandardName = "Standard 1", Description = 
    "First Standard" });
    defaultStandards.Add(new Standard() { StandardName = "Standard 2", Description = 
    "Second Standard" });
    defaultStandards.Add(new Standard() { StandardName = "Standard 3", Description = 
    "Third Standard" });

    context.Standards.AddRange(defaultStandards);

    base.Seed(context);
    }
 }

現在,如下所示在上下文類中設置該數據庫初始化程序類。

  public class SchoolContext: DbContext 
  {
    public SchoolContext(): base("SchoolDB") 
    {
       Database.SetInitializer(new SchoolDBInitializer());
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM