【问题标题】:How should I seed data in Entity Framework 6我应该如何在 Entity Framework 6 中播种数据
【发布时间】:2021-10-17 03:06:41
【问题描述】:

我在将数据播种到数据库时遇到问题。早些时候我从这个 tut 中尝试过:Seed Data in EF 6 Code-First 然后永远不会调用种子方法

DBSchool.cs

namespace SchoolTest.DAL
{
    public class DBSchool : DbContext
    {
        public DBSchool() : base("DBSchool")
        {
            Database.SetInitializer(new Seeder());
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

        public DbSet<Guest> Guests { get; set; }
    }
}

Seeder.cs

public class Seeder : DropCreateDatabaseAlways<DBSchool>
    {
        protected override void Seed(DBSchool context)
        {
            IList<Guest> GuestList = new List<Guest>();
            GuestList.Add(new Guest()
            {
                Name = "Dexter",
                Surname = "Dexter",
                Email = "test@test.com"
            });

            context.Guests.AddRange(GuestList);
            context.SaveChanges();
            base.Seed(context);
        }
    }

Guest.cs

public class Guest
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public string Email { get; set; }
        [Key]
        public int GuestId { get; set; }
    }

App.config

  <appSettings>
    <add key="DatabaseInitializerForType SchoolTest.DAL.DBSchool, SchoolTest"
        value="SchoolTest.Data.Seeder, SchoolTest" />
  </appSettings>

有什么方法可以调用 Seed() 方法还是只通过 Configuration.cs?

【问题讨论】:

    标签: c# entity-framework entity-framework-6 entity-framework-migrations seed


    【解决方案1】:

    尝试像这样更改您的代码。

    public class DBSchool : DbContext
    {
        public DBSchool() : base("name=<database-name>")
        {
            Database.SetInitializer<DBSchool>(new Seeder());
        }
    
        // Rest of your implementation
    }
    

    &lt;database-name&gt; 替换为您的数据库名称。

    如果不起作用,您可以为上下文类提供一个通用类型参数,并按如下方式更改您的代码。

    Seeder.cs -> public class Seeder&lt;T&gt; : DropCreateDatabaseAlways&lt;DBSchool&gt;

    DBSchool.cs -> Database.SetInitializer&lt;DBSchool&gt;(new Seeder&lt;DBSchool&gt;());

    阅读更多关于here的信息。

    如果也不起作用,您可以使用 custom sqlSql() 使用迁移和种子数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-20
      • 2021-06-30
      • 2016-05-14
      • 2017-12-22
      • 2020-05-23
      • 1970-01-01
      • 2011-09-12
      • 2016-04-04
      相关资源
      最近更新 更多