向EF6 FluentAPI添加列名称约定 [英] Add Column Name Convention to EF6 FluentAPI
问题描述
这个问题是在4年前被问到的: EF Mapping to表示表格中的所有列名称我希望有更好的处理这些天。
我使用的是EF6 Fluent API,将调用代码优先而不迁移。我的模型有POCO,我的大多数数据库列名定义为 [SingularTableName] Field
(例如,CustomerAddress db列映射到Customers POCO中的Address字段) / p>
表:
CREATE TABLE dbo 。客户(
- ID,时间戳等)
CustomerName NVARCHAR(50),
CustomerAddress NVARCHAR(50)
- 等
);
型号:
public class Customer
{
// id,timestamp,etc
public string Name {get; set;}
public string地址{get; set;}
}
ModelBuilder:
modelBuilder< Customer>()
.Property(x => x.Name).HasColumnName(CustomerName );
modelBuilder< Customer>()
.Property(x => x.Address).HasColumnName(CustomerAddress);
目标:
我真正想要的是能够为FluentAPI说出这样的东西:
modelBuilder< Customer> ().ColumnPrefix( 客户);
//仅处理非常规字段名称
//而不必为每列列出列名
使用基于模型的代码优先约定已经变得非常简单。只需创建一个实现 IStoreModelConvention的类
...
class PrefixConvention: IStoreModelConvention< EdmProperty>
{
public void Apply(EdmProperty属性,DbModel模型)
{
property.Name = property.DeclaringType.Name + property.Name;
}
}
...并将其添加到 OnModelCreating
:
modelBuilder.Conventions.Add(new PrefixConvention());
This question was asked here 4 years ago: EF Mapping to prefix all column names within a table I'm hoping there's better handling these days.
I'm using EF6 Fluent API, what I'll call Code First Without Migrations. I have POCOs for my models, and the majority of my database column names are defined as [SingularTableName]Field
(e.g., CustomerAddress db column maps to Address field in Customers POCO)
Table:
CREATE TABLE dbo.Customers (
-- ID, timestamps, etc.
CustomerName NVARCHAR(50),
CustomerAddress NVARCHAR(50)
-- etc.
);
Model:
public class Customer
{
// id, timestamp, etc
public string Name {get;set;}
public string Address {get;set;}
}
ModelBuilder:
modelBuilder<Customer>()
.Property(x => x.Name).HasColumnName("CustomerName");
modelBuilder<Customer>()
.Property(x => x.Address).HasColumnName("CustomerAddress");
Goal:
What I'd really like is to be able to say something like this for the FluentAPI:
modelBuilder<Customer>().ColumnPrefix("Customer");
// handle only unconventional field names here
// instead of having to map out column names for every column
With model-based code-first conventions this has become very simple. Just create a class that implements IStoreModelConvention
...
class PrefixConvention : IStoreModelConvention<EdmProperty>
{
public void Apply(EdmProperty property, DbModel model)
{
property.Name = property.DeclaringType.Name + property.Name;
}
}
... and add it to the conventions in OnModelCreating
:
modelBuilder.Conventions.Add(new PrefixConvention());
这篇关于向EF6 FluentAPI添加列名称约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!