You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6 MVC数据库优先模式查询AdventureWorks遇SqlException错误

解决ASP.NET Core 6 MVC中访问AdventureWorks Production.Product表的"Invalid object name 'Products'"错误

问题根源是EF Core默认会将DbSet<Product>的名称Products作为数据库表名,而实际目标表是Production架构下的Product表,必须明确指定表的架构和名称,以下是两种可行方案:

方案一:使用数据注解配置实体

在你的Product实体类上添加[Table]特性,指定表名和所属架构:

using System.ComponentModel.DataAnnotations.Schema;

[Table("Product", Schema = "Production")]
public class Product
{
    // 实体属性示例
    public int ProductID { get; set; }
    public string Name { get; set; }
    // 其他对应Production.Product表的属性
}

方案二:使用Fluent API配置上下文

在AppDbContext的OnModelCreating方法中,通过Fluent API指定实体对应的表和架构:

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

    public DbSet<Product> Products { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // 绑定Product实体到Production.Product表
        modelBuilder.Entity<Product>()
            .ToTable("Product", "Production");
    }
}

额外验证点

  • 再次确认连接字符串中的数据库名称是否正确指向AdventureWorks实例,示例连接字符串格式:
    "ConnectionStrings": {
      "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=AdventureWorks;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
    
  • 确保Product实体的所有属性与Production.Product表的字段名称、数据类型完全匹配。

内容的提问来源于stack exchange,提问作者Imesashvili_Irakli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 14:40:17