问题描述
这个问题是 4 年前在这里提出的:EF 映射为表中的所有列名添加前缀我希望这些天有更好的处理方式.
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.
我正在使用 EF6 Fluent API,我将其称为 Code First without Migrations.我的模型有 POCO,并且我的大部分数据库列名都定义为 [SingularTableName]Field
(例如,CustomerAddress db 列映射到 Customers POCO 中的 Address 字段)
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)
表格:
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 说这样的话:
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 基于模型的代码优先约定 这变得非常简单.只需创建一个实现 IStoreModelConvention
...
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;
}
}
...并将其添加到 OnModelCreating
中的约定中:
... and add it to the conventions in OnModelCreating
:
modelBuilder.Conventions.Add(new PrefixConvention());
这篇关于将列名称约定添加到 EF6 FluentAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!