【发布时间】:2022-11-30 16:57:33
【问题描述】:
我有一个数据库,它存在于 3 个不同的阶段服务器上。
所有三台服务器上的数据库都是相同的。
我编写了一个应用程序来根据某些逻辑同步数据库表。
对于这种方法,我编写了一个包含实体的通用数据库上下文,因为它们在所有服务器上都是相同的:
public abstract class GenericContext : DbContext
{
public GenericContext(DbContextOptions<ContextA> options)
: base(options)
{
}
public GenericContext(DbContextOptions<ContextB> options)
: base(options)
{
}
public GenericContext(DbContextOptions<ContextC> options)
: base(options)
{
}
public DbSet<Application> Applications { get; set; }
[...]
}
这背后的想法是集中处理Application这样的实体。
实体应用程序看起来像:
[Table("Applications", Schema = "dbo")]
public class Application
{
public string Alias { get; set; }
[Key]
public int Id { get; set; }
[...]
}
在我的启动类中,我用它们匹配的 DbContextOptions 注册了所有 3 个上下文。
采用该方法的原因是我的存储库需要一个通用上下文来最小化处理 3 种不同数据库类型的开销。 这方面的一个例子是:
public int AddApplication(GenericContext context, Application entity)
{
context.Applications.Add(entity);
return entity.Id;
}
当我启动我的应用程序时,一切正常,直到我尝试访问其中一个上下文并且它们真正建立起来。 然后抛出以下异常:
Cannot use table 'dbo.Applications' for entity type 'Application'
since it is being used for entity type 'Application' and potentially other
entity types, but there is no linking relationship.
Add a foreign key to 'Application' on the primary key properties and
pointing to the primary key on another entity type mapped to 'dbo.Applications'.
正如异常所述,似乎不可能为多个上下文重用表实体。
有没有办法以所需的集中方式管理实体但避免异常?
【问题讨论】:
-
为什么?您可以使用不同的连接字符串重用相同的
DbContext。 -
@SvyatoslavDanyliv,我编辑了我的请求以澄清它。
标签: c# entity-framework-core dbcontext