Add Column Name Convention to EF6 FluentAPI

ef-fluent-api entity-framework entity-framework-6

Question

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
3
5/23/2017 12:13:45 PM

Accepted Answer

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());
3
11/18/2016 12:31:32 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow