Search code examples
entity-frameworkef-code-firstcode-firstentity-framework-migrations

How to initialize seed data from another DbContext


My project has 2 DbContext (in 2 Entity Framework project): CoreDbContext and Module1DbContext

In CoreDbContext I have 1 table named SystemStatus. So is it possible to insert seed data to this table from Module1DbContext? I tried to pass CoreDbContext to Seed method in Module1DbContext but it did work.


Solution

  • Yes. Just new up the other context and do what you need. If the CoreDbContext is in another project you will need to reference it.

    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();
            }
        }
    }