Add Column Name Convention to EF6 FluentAPI

2020-02-14 06:37发布

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

1条回答
可以哭但决不认输i
2楼-- · 2020-02-14 07:38

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());
查看更多
登录 后发表回答