加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 实体框架:构建初始数据库时只有种子

发布时间:2020-12-15 07:41:20 所属栏目:百科 来源:网络整理
导读:我正在使用Entity Framework 6和这个DbMigrationsConfiguration: public sealed class Configuration : DbMigrationsConfigurationDataContext{ public Configuration() { AutomaticMigrationsEnabled = true; } protected override void Seed(Danfoss.Ener
我正在使用Entity Framework 6和这个DbMigrationsConfiguration:
public sealed class Configuration : DbMigrationsConfiguration<DataContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(Danfoss.EnergyEfficiency.Data.DataContext context)
    {
        //Adding initial data to context

        context.SaveChanges();
    }

}

我以这种方式在WebAPI中使用它:

public static void Register(HttpConfiguration config)
{
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext,Configuration>());
}

我注意到每次我的应用程序启动时,Seed函数都在运行.我怎么能阻止这个?我只喜欢它在第一次运行时运行,当它构建初始表时.

解决方法

每次调用Update-Database时都会调用DbMigrationsConfiguration.Seed方法.其背后的原因在本博客中由 One Unicorn解释.

这意味着您必须编写种子代码以应对现有数据.如果您不喜欢,可以在CodePlex投票支持更改.

与此同时,引用博客:

The best way to handle this is usually to not use AddOrUpdate for
every entity,but to instead be more intentional about checking the
database for existing data using any mechanisms that are appropriate.
For example,Seed might check whether or not one representative entity
exists and then branch on that result to either update everything or
insert everything

我过去使用的另一个选项是使用Sql命令添加与迁移本身中的迁移相关的常设数据.这样它只运行一次.我倾向于放弃这一点,因为我更愿意将播种放在一个地方.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读