Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework column mapping for complex types

I have complex type class ..Here is hierarchy

 public class Item 
 {
    public virtual Summary Summary { get; set; }
 }

 public class Summary
 {
    public int Id { get; set; }

    [Key, ForeignKey("Item")]
    public int ItemId { get; set; }

    public virtual Item Item { get; set; }

    public virtual ClaimSummary Cost { get; set; }
 }

    [ComplexType]
    public class ClaimSummary
    {
        public virtual decimal? SparePartsCost { get; set; }

        public virtual decimal? LaborHours { get; set; }
                  .....
    }

When I save Item into DB, SQL profiler shows it expects column names as Cost_SparePartsCost where my DB has column name as SparePartsCost. I purposefully created DB column names such a way since I dont want '_' in between names.

How can I let Entity Framework know that columns are mapped such a way that it will ignore its default mapping and follow the custom mapping ?

like image 732
user1532976 Avatar asked Sep 12 '17 19:09

user1532976


1 Answers

You can override the default EF complex type column name convention in a serveral ways.

If you want to avoid the prefix in all entities using the complex type, you can use either data annotations (Column attribute):

[ComplexType]
public class ClaimSummary
{
    [Column("SparePartsCost")]
    public virtual decimal? SparePartsCost { get; set; }

    [Column("LaborHours")]
    public virtual decimal? LaborHours { get; set; }

    // ...
}

or fluent configuration:

modelBuilder.ComplexType<ClaimSummary>()
    .Property(e => e.SparePartsCost).HasColumnName("SparePartsCost");
modelBuilder.ComplexType<ClaimSummary>()
    .Property(e => e.LaborHours).HasColumnName("LaborHours");

If you want to override the default convention just for some entity (like your Summary), then you can use fluent configuration at entity level like this:

modelBuilder.Entity<Summary>()
    .Property(e => e.Cost.SparePartsCost).HasColumnName("SparePartsCost");
modelBuilder.Entity<Summary>()
    .Property(e => e.Cost.LaborHours).HasColumnName("LaborHours");

Reference: Associations in EF Code First: Part 2 – Complex Types

like image 193
Ivan Stoev Avatar answered Oct 07 '22 22:10

Ivan Stoev