如何从另一个DbContext初始化种子数据

时间:2017-10-02 02:19:32

标签: entity-framework ef-code-first code-first ef-migrations

我的项目有2个DbContext(在2个实体框架项目中):CoreDbContextModule1DbContext

CoreDbContext我有一个名为SystemStatus的表。那么可以从Module1DbContext向此表插入种子数据吗?我试图将CoreDbContext传递给Module1DbContext中的Seed方法,但它确实有效。

1 个答案:

答案 0 :(得分:1)

是。只是新的其他背景,做你需要的。如果CoreDbContext在另一个项目中,您将需要引用它。

protected override void Seed(Module1DbContext context)
{
    // get some data from the current context you want to use for seeding
    var someItemFromM1 = context.FooBar.FirstOrDefault(fb => fb.Id == myID);
    if (someDataFromM1 != null)
    {
        using (var coreContext = new CoreDbContext())
        {
            // Using AddOrUpdate which is designed for seeding, but you could just use standard update code
            coreContext.SystemStatuses.AddOrUpdate(
                ss => ss.Code,  // Unique field to check so duplicate not added
                new SystemStatus
                {
                    Code = someItemFromM1.Code,
                    Description = someItemFromM1.Description
                });
            coreContext.SaveChanges();
        }
    }
}