【发布时间】:2015-03-18 18:04:41
【问题描述】:
有人知道是否可以根据类的命名空间设置代码优先类的表模式吗?
例如,命名空间Core.Foo 中的每个类都将具有Foo 的架构。
【问题讨论】:
-
您是否尝试在模型构建器中设置模式名称?
标签: entity-framework
有人知道是否可以根据类的命名空间设置代码优先类的表模式吗?
例如,命名空间Core.Foo 中的每个类都将具有Foo 的架构。
【问题讨论】:
标签: entity-framework
好吧,您可以使用以下两个选项之一指定架构名称:
[Table("TableName","Foo")]
public class Entity
{
}
使用Fluent Api:
modelBuilder.Entity<Entity>().ToTable("TableName", "Foo");
在这个主题上挖掘更多,我认为您正在寻找的是 EF 的Custom Convention:
public class CustomSchemaConvention : Convention
{
public CustomSchemaConvention()
{
Types().Configure(c => c.ToTable(c.ClrType.Name, c.ClrType.Namespace.Substring(c.ClrType.Namespace.LastIndexOf('.') + 1)));
}
}
然后,在您的上下文中,您需要覆盖 OnModelCreating 方法以添加新约定:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new CustomSchemaConvention());
}
【讨论】:
在 EF 6.2 或 EF Core 中,使用 Schema 属性为 Db 表指定架构名称,如下所示:
[Table("TableName", Schema = "Foo")]
public class Entity
{
//Properties
}
【讨论】:
我将在 octavioccl 提供的内容中添加一件事。如果您想保留表名复数,可以使用内置复数服务,如下所示:
using System.Data.Entity.Infrastructure.DependencyResolution;
public class CustomSchemaConvention : Convention
{
public CustomSchemaConvention()
{
var pluralizationService = DbConfiguration.DependencyResolver.GetService<IPluralizationService>();
Types().Configure(c => c.ToTable(
pluralizationService.Pluralize(c.ClrType.Name),
c.ClrType.Namespace.Substring(c.ClrType.Namespace.LastIndexOf('.') + 1))
);
}
}
【讨论】: