gpt4 book ai didi

c# - 使用同一个数据库为多个 DbContext 创建表

转载 作者:太空宇宙 更新时间:2023-11-03 15:04:45 26 4
gpt4 key购买 nike

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

它在第一个 DbContext 对象上调用 DataBase.EnsureCreated() 时起作用,但它不会为其余对象创建表。在 Init.Initalize() 之后,我希望数据库包含两个名为 Clients 和 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
}

最佳答案

您是否尝试过定义一个配置,在其中为每个单独的上下文设置 ContextKey

例如:

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

}

关于c# - 使用同一个数据库为多个 DbContext 创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44265244/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com