entity-frameworkdictionaryforeign-keysfluent-interfaceentity-framework-ctp5

Mapping properties to (differently named) foreign key fields in Entity Framework CTP5


I'm trying to use the Entity Framework CTP5 Fluent API to map an exist database. I have the following classes:

public class Shop
{
    public long Id
    {
        get;
        set;
    }
}

public class Sale
{
    public long Id
    {
        get;
        set;
    }

    public virtual Shop Shop
    {
        get;
        set;
    }
}

The corresponding tables are called "Stores" and "Sales". Sales has a StoreId foreign key that points to the Id field in the Stores table.

I'm struggling to map the Sale.Shop.Id to the StoreId in the table. I'm not at liberty to change it to ShopId, so need to map it.

In CTP4, I was using:

modelBuilder.Entity<Sale>().MapSingleType(x =>
    new
    {
        Id = x.Id,
        StoreId = x.Shop.Id
    });

I tried the following:

modelBuilder.Entity<Sale>().Property(x => x.Shop.Id).HasColumnName("StoreId");

However, it seems this only works with a primitive type.

How do I specify this mapping?


Solution

  • I think the best way to solve this would be to upgrade your independent Association to be a Foreign Key Association meaning that instead of hiding the foreign key ShopId, actually including it in Sale class. Then you can use Data Aannotations/Fluent API to change its column name to match to your existing schema:

    public class Shop
    {
        public long Id { get;set; }
    }
    
    public class Sale
    {
        public long Id { get; set; }
    
        [Column(Name="StoreID")]
        public long ShopId { get; set; }
    
        public virtual Shop Shop { get; set; }
    }
    


    Which results to the desired DB Schema: alt text