Code Pope
Code Pope

Reputation: 5459

EF6: PrimitivePropertyConfiguration.HasColumnName vs. DataAnnotations.Schema.ColumnAttribute

If the name of a field in a table of my database differs from the name of the property in my domain class, there are, to the best of my knowledge, two different ways to solve that: Let's imagine, we have table Author with a field FIRST_NAME and in the code we have an entity Author with a property FirstName, then:
1.Using PrimitivePropertyConfiguration.HasColumnName:

modelBuilder.Entity<Author>().Property(e => e.FirstName).HasColumnName("FIRST_NAME");

2.Use Annotations:

[Column("FIRST_NAME")] 
public String FirstName { get; set; }

My question is if there is difference between these two options and when to prefer one of them over the other one?

Upvotes: 1

Views: 312

Answers (1)

Babak Naffas
Babak Naffas

Reputation: 12571

I prefer the annotations as it's the simplest for maintenance and human reference; this is with the caveat that you have access to the class you're using for the entity.

I consider the model builder to be similar to extensions where it allows you to leverage classes that you can access from references and packages.

So in your example, if Author is a class in your solution, I'd use annotations. But if the same class was from a Nuget package then I'd have no option but to use the model builder.

Upvotes: 2

Related Questions