我尝试在 ASP.NET Core 应用程序中使用 Entity Framework 设置数据库连接,但每次尝试从数据上下文中读取时,都会失败,表明我尝试获取的表无效。
我对 EF 和 ASP.NET Core 比较陌生,所以我可能会遗漏一些明显的东西。如何让 EF 连接/查找我的对象?
我的连接字符串如下:
Data Source=DbServer;Initial Catalog=AIT;Integrated Security=True
我尝试读取的表位于DbServer
上:
AIT.processing.orderProcessing
当数据库上下文尝试连接时出现的错误是这样的:
SqlException: Invalid object name 'processing.orderProcessing'.
我在运行时查看了上下文本身,它正在连接到正确的服务器。我还验证了数据库的连接字符串是否正确,并且它包含 processing.orderProcessing
表。我还尝试明确告诉 EF 它应该通过使用我的 c# 类上的 Table 属性连接到特定对象:
[Table("AIT.processing.orderProcessing")]
这只会导致我的错误消息更改为:
SqlException: Invalid object name 'AIT.processing.orderProcessing'.
据我所知,如果它连接到DBServer
,它应该能够找到该表,因为它确实存在,并且拼写正确。我只是从 SSMS 复制/粘贴它来确认。
编辑: 下面的答案是为我解决的。将我的表属性更改为:
[Table("orderProcessing", Schema = "processing")]
使 EF 能够连接。
最佳答案
如果您的数据库名称是“AIT”并且架构是“processing”,您必须在 EF core 中表达您的架构名称。
protected override void OnModelCreating(ModelBuilder builder)
{
builder.HasDefaultSchema("processing");
}
关于c# - 使用 Entity Framework 读取 SQL Server 表时对象名称无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56484929/