使用默认 Table 名称和带有 EF 代码的自定义架构
Use Default Table Name & Custom Schema w/ EF Code First
使用 EF 代码 首先,我想为 table 指定一个架构 (Data
),但让 EF 使用其默认约定来命名 table .
我正在使用 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 使用其约定来命名 table。
我试图用空字符串设置 Name
。
[Table("", Schema = "Data")]
抛出以下 - 非常合理,符合预期 - 错误:
The argument 'name' cannot be null, empty or contain only white space.
有什么方法可以让 EF 在指定架构时默认使用其 table 名称约定?
这无法完成,因为 Table
属性只有一个构造函数,需要指定 Name
。
请参考MSDN - TableAttribute Constructor
public TableAttribute(
string name
)
Slava Utesinov 建议使用 modelBuilder.HasDefaultSchema("Data");
设置默认模式。
当只有一个模式希望设置时,这将起作用;但是,如果要应用多个架构,则无需手动设置 Table 名称。
public class ExampleContext: DbContext
{
public ExampleContext() : base("ExampleContext") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("Data");
///...
}
使用 EF 代码 首先,我想为 table 指定一个架构 (Data
),但让 EF 使用其默认约定来命名 table .
我正在使用 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 使用其约定来命名 table。
我试图用空字符串设置 Name
。
[Table("", Schema = "Data")]
抛出以下 - 非常合理,符合预期 - 错误:
The argument 'name' cannot be null, empty or contain only white space.
有什么方法可以让 EF 在指定架构时默认使用其 table 名称约定?
这无法完成,因为 Table
属性只有一个构造函数,需要指定 Name
。
请参考MSDN - TableAttribute Constructor
public TableAttribute(
string name
)
Slava Utesinov 建议使用 modelBuilder.HasDefaultSchema("Data");
设置默认模式。
当只有一个模式希望设置时,这将起作用;但是,如果要应用多个架构,则无需手动设置 Table 名称。
public class ExampleContext: DbContext
{
public ExampleContext() : base("ExampleContext") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("Data");
///...
}