引用实体框架中表的架构名称

本文关键字:实体 框架 引用 | 更新日期: 2023-09-27 17:58:41

如何明确地告诉EF表位于特定模式中?

例如,AdventureWorks数据库定义了Production.Product表。当使用OnModelCreating方法时,我使用以下代码:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    EntityTypeConfiguration<Product> config = modelBuilder.Entity<Product>();
    config.HasKey(p => p.ProductID);
    config.Property(p => p.Price).HasColumnName("ListPrice");
    config.ToTable("Product");
}

然而,当它运行时,它会说它是Invalid object name: dbo.Product

我试过:

config.ToTable("Production.Product");
//and
config.HasEntityName("Production");

但两者都失败了。

引用实体框架中表的架构名称

ToTable有重载版本,它接受两个参数:表名和模式名,因此正确的版本是:

config.ToTable("Product", "Production");

也可以使用"table"属性上的可选参数"schema"使用数据注释来指定表架构。

using System.ComponentModel.DataAnnotations.Schema;
[Table("Product", Schema="Production")]
public class Product
{
    public int ProductID { get; set; }
    public decimal Price { get; set; }
}