c# - Entity Framework : Can DB Contexts Have Foreign Keys Across Different Schemas?

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

<分区>

我们有一个包含多个模式的数据库。公司架构师希望每个模式都有 Entity Framework DbContext。此外,不同模式之间存在外键关系。

今天在构建架构时,收到此错误:

错误:

For foreign key FK_Customer_TransactionId on table CustomerTransaction, Unable to model the end of the foreign key on principal table inv.Product. This is usually because the principal table was not included in the selection set."

我需要一个模式和来自另一个模式的 1 个表。它无法在附加模式上找到父表来创建外键。

寻找解决方案:

(1) 为每个模式设置多个数据库上下文,在不同模式之间使用外键,这通常是不好的做法吗? Microsoft 和 Entity Framework 支持吗?

(2) 在 Entity Framework Core Scaffold 中,是否可以搭建一个架构以及来自另一个架构的附加父表?

(3) 或者是否有方法可以忽略外部模式的外键属性?

dotnet ef dbcontext scaffold 
   "Server=localhost;Database=DatabasetestTest;Trusted_Connection=True;" 
   Microsoft.EntityFrameworkCore.SqlServer -c DatabaseContext 
   -o Entities\Scaffold 
   -f 
   --project C:\Project 
   --schema CustomerService

目前使用 EF Core 2.2

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

Using Entity Framework 6 with Multiple DB Schemas but using One DBContext

最佳答案

(1) Is it bad practice in general to have multiple db contexts for every schema, with foreign keys between different schemas? Do Microsoft and Entity Framework support this?

我不认为有多个模式或/和 DbContext 或模式之间的关系是不好的做法。 Entity Framework 支持它。无论如何,我建议考虑这样做,因为将来您最终可能会拥有太多的数据库上下文,并且可能会变得一团糟。

(2) In Entity Framework Core Scaffold, Is there anyway to scaffold a schema And an additional parent table from another schema?

是的。您可以构建多个方案和表格。唯一的问题是您必须为脚手架指定具体的方案和表格。

dotnet ef dbcontext scaffold 
   "Server=localhost;Database=DatabasetestTest;Trusted_Connection=True;" 
   Microsoft.EntityFrameworkCore.SqlServer -c DatabaseContext 
   -o Entities\Scaffold 
   -f 
   --project C:\Project 
   --schema CustomerService
   --schema AnotherSchema
   --schema YetAnotherSchema
   --table Table1
   --table Table2
   --table Table3
   --table TableX

(3) Or is there method to ignore foreign key property on outside schemas?

我不这么认为。每当两个表彼此之间有关系时,您都必须符合它。如果您想要构建表 inv.Product 中 FK 引用的表 CustomerService.CustomerTransaction 的脚手架,您必须在脚手架中包含架构“inv”和表“Product”。您可能会收到另一个错误,因为可能与您要包含的表有其他关系。您最终可能会搭建整个数据库。

关于c# - Entity Framework : Can DB Contexts Have Foreign Keys Across Different Schemas?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57485837/

相关文章:

entity-framework - 使用 Repository/UoW/DI 抽象 EntityFramework.dll 引用

c# - 使用 Visual Studio 事后调试 C# 应用程序

c# - 从 C DLL 到 .NET 的接口(interface)

c# - Rowid中的SQLITE问题

c# - WCF、声明、ADFS 3.0

c# - EF Core 过滤 + 子实体分页

c# - 迁移 "our target project ' xxx' 与您的迁移程序集 'xxx' 不匹配“使用 aspnet Core 1.0 RC2 -

c# - 使用 linq 实例化包含其他对象列表的对象,其中查询条件位于内部列表上

c# - Datagridview 上 ComboBoxColumn 中的 "SelectedIndexChanged"事件

entity-framework - 在运行时更改表名