3

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
Community
  • 1
  • 1
jleach
  • 7,410
  • 3
  • 33
  • 60

1 Answers1

3

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());
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
  • Thanks. I skimmed it quickly but will have to dig in a bit later. Question: I'm not using an EDMX model, just POCOs and the fluent API config with db initialize off. Is this still applicable without the EDMX models (I ask because I see the EdmProperty, which I'm unfamiliar with offhand). – jleach Nov 18 '16 at 12:51
  • What's more, it can *only* be used with code-first :) But in the background, EF always builds an EDM (Entity data Model), hence the name EdmProperty. – Gert Arnold Nov 18 '16 at 12:55
  • Excellent. This looks great - I didn't actually expect an answer to this, so I'm very glad to see it! – jleach Nov 18 '16 at 13:10
  • I've got a bunch of `Name: Each property name in a type must be unique. Property name ... is already defined.` when running `add-migration` after adding this – Toolkit Oct 25 '17 at 06:18
  • @Toolkit Please ask a new question so you give all required details. – Gert Arnold Oct 25 '17 at 06:54