这个问题在4年前被问到:EF Mapping to prefix all column names within a table我希望这些日子有更好的处理。
我使用的是EF6 Fluent API,我称之为Code First Without Migrations。我的模型有POCO,我的大多数数据库列名都定义为[SingularTableName]Field
(例如,CustomerAddress db列映射到Customers POCO中的Address字段)
表格
CREATE TABLE dbo.Customers (
-- ID, timestamps, etc.
CustomerName NVARCHAR(50),
CustomerAddress NVARCHAR(50)
-- etc.
);
型号:
public class Customer
{
// id, timestamp, etc
public string Name {get;set;}
public string Address {get;set;}
}
模型构建器:
modelBuilder<Customer>()
.Property(x => x.Name).HasColumnName("CustomerName");
modelBuilder<Customer>()
.Property(x => x.Address).HasColumnName("CustomerAddress");
目标:
我真正喜欢的是能够为FluentAPI说出类似的内容:
modelBuilder<Customer>().ColumnPrefix("Customer");
// handle only unconventional field names here
// instead of having to map out column names for every column
答案 0 :(得分:3)
使用model-based code-first conventions这变得非常简单。只需创建一个实现IStoreModelConvention
...
class PrefixConvention : IStoreModelConvention<EdmProperty>
{
public void Apply(EdmProperty property, DbModel model)
{
property.Name = property.DeclaringType.Name + property.Name;
}
}
...并将其添加到OnModelCreating
中的约定:
modelBuilder.Conventions.Add(new PrefixConvention());