使用相同的数据库

时间:2017-05-30 14:37:17

标签: c# entity-framework asp.net-core entity-framework-core

我正在尝试实现针对同一数据库的多个DbContext。

在第一个DbContext对象上调用DataBase.EnsureCreated()时它会起作用,但它不会为其余对象创建表。 在Init.Initalize()之后,我希望数据库包含两个名为Clients and Addresses的表

初始化数据库:

public static class Init
{
    public static void Initalize(BaseDbContext[] contexts, Config.Options.Environments environment)
    {                     
        if (environment == Config.Options.Environments.Development)
        {
            contexts[0].Database.EnsureDeleted();

            foreach(BaseDbContext context in contexts)
            {
                context.Database.EnsureCreated();
            }

            var clients = new Client[]
            {
                new Client() { Key = Guid.NewGuid(), Name = "Smokers.no", DisplayName = "Smokers.no", Email = "post@smokers.no", LogoFilename = "logo.jpg" }
            };

            foreach(BaseDbContext context in contexts)
            {
                if (context.GetType().Equals(typeof(Data.SharedDbContext)))
                {
                    var cntx = context as Data.SharedDbContext;
                    foreach (Client client in clients) { cntx.Clients.Add(client); }
                    cntx.SaveChanges();
                }
            }


        }
        else
        {
            foreach(BaseDbContext context in contexts)
            {
                context.Database.EnsureCreated();

                if (context.GetType().Equals(typeof(Data.SharedDbContext)))
                {
                    var cntx = context as Data.SharedDbContext;

                    if (cntx.Clients.Any())
                    {
                        return;
                    }
                }
            }
        }
    }
}

BaseDbContext:

public class BaseDbContext : DbContext
{
    public BaseDbContext(DbContextOptions<BaseDbContext> options) : base(options) { }
}

SharedDbContext:

public class SharedDbContext : BaseDbContext
{
    public SharedDbContext(DbContextOptions<BaseDbContext> options) : base(options) { }

    #region DbSets
    public DbSet<Client> Clients { get; set; }
    #endregion
}

MailerDbContext:

public class MailerDbContext : BaseDbContext
{
    SharedDbContext _context;

    public MailerDbContext(DbContextOptions<BaseDbContext> options, SharedDbContext context) : base(options)
    {
        _context = context;
    }

    public SharedDbContext LCToolsContext
    {
        get
        {
            return _context;
        }
    }

    #region DbSets
    public DbSet<Address> Addresses { get; set; }
    #endregion
}

2 个答案:

答案 0 :(得分:0)

您是否尝试过为每个单独的上下文设置ContextKey的配置?

E.g:

public sealed class Configuration : DbMigrationsConfiguration<MyDataContext>
{
 public Configuration()
 {
   AutomaticMigrationsEnabled = false;
   ContextKey = "MySpecialKey";
 }

 //Seed method here..

}

这样称呼:

private static void InitializeDatabaseUsingEF()
{

  System.Data.Entity.Database.SetInitializer(
    new System.Data.Entity.MigrateDatabaseToLatestVersion<
      MyDataContext,
      Migrations.Configuration>("ConnectionString.PostgreSql (Npgsql)"));

  using (var db = new MyDataContext())
  {
    db.Database.Initialize(true);        
  }

}

答案 1 :(得分:0)

我最终改变了设计,现在一切都按预期工作了。

初始化数据库:

public static class Init
{
    public static void Initalize(DbContext[] contexts, Config.Options.Environments environment)
    {                     
        if (environment == Config.Options.Environments.Development)
        {
            foreach(DbContext cntx in contexts)
            {
                if (cntx.GetType().Equals(typeof(GenericDbContext)))
                {
                    cntx.Database.EnsureDeleted();
                    cntx.Database.EnsureCreated();
                }
            }

            var clients = new Client[]
            {
                new Client() { Key = Guid.NewGuid(), Name = "Smokers.no", DisplayName = "Smokers.no", Email = "post@smokers.no", LogoFilename = "logo.jpg" }
            };

            foreach(DbContext cntx in contexts)
            {
                if (cntx.GetType().Equals(typeof(GenericDbContext)))
                {
                    var context = cntx as GenericDbContext;
                    foreach (Client client in clients) { context.Clients.Add(client); }
                    context.SaveChanges();
                }
            }
        }
        else
        {
            foreach(DbContext cntx in contexts)
            {
                cntx.Database.EnsureCreated();

                if (cntx.GetType().Equals(typeof(GenericDbContext)))
                {
                    var context = cntx as GenericDbContext;
                    if (context.Clients.Any())
                    {
                        return;
                    }
                }
            }
        }
    }
}

<强> GenericDbContext:

public class GenericDbContext : DbContext
{
    public GenericDbContext(DbContextOptions<GenericDbContext> options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Models.Mailer.Address>().ToTable("MailerAddresses");
    }

    public DbSet<Client> Clients { get; set; }
    public DbSet<Models.Mailer.Address> MailerAddresses { get; set; }
}

<强> MailerDbContext:

public class MailerDbContext : DbContext
{
    public MailerDbContext(DbContextOptions<MailerDbContext> options, GenericDbContext generic) : base(options)
    {
        this.GenericDbContext = generic;
    }

    public GenericDbContext GenericDbContext { get; set; }
}