【问题标题】:Use Default Table Name & Custom Schema w/ EF Code First使用带 EF 代码的默认表名称和自定义架构
【发布时间】:2018-01-24 15:22:18
【问题描述】:

使用 EF 代码 首先,我想为表指定架构 (Data),但让 EF 使用其默认约定来命名表。

我正在使用DataAnnotations.Schema TableAnnotations 来设置架构。

[Table("Customers", Schema = "Data")]
public class Customer
{
    public int Id{ get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

但这需要我手动设置Name,而我希望EF 使用它的约定来命名表。

我尝试将Name 设置为空字符串。

[Table("", Schema = "Data")]

这会引发以下 - 非常合理的预期 - 错误:

参数“名称”不能为空、空或仅包含空格。

在指定架构时,有什么方法可以让 EF 默认使用其表名约定?

【问题讨论】:

  • modelBuilder.HasDefaultSchema("Data");

标签: c# entity-framework ef-code-first


【解决方案1】:

这不能做到,因为Table 属性只有一个构造函数,需要指定Name

请参考MSDN - TableAttribute Constructor

public TableAttribute(
string name
)

【讨论】:

    【解决方案2】:

    Slava Utesinov 建议使用modelBuilder.HasDefaultSchema("Data"); 设置默认schma。

    当人们只希望设置一个模式时,这将起作用;但是,当需要应用多个模式时将无法正常工作,而无需手动设置表名称。

    public class ExampleContext: DbContext
    {
        public ExampleContext() : base("ExampleContext") { }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.HasDefaultSchema("Data");
            ///...
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-15
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      相关资源
      最近更新 更多