Add Column Name Convention to EF6 FluentAPI

做~自己de王妃 提交于 2019-12-29 08:57:20

问题


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:


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());


来源:https://stackoverflow.com/questions/40674883/add-column-name-convention-to-ef6-fluentapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!