3

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?

dommer
  • 19,610
  • 14
  • 75
  • 137

3 Answers3

9

Update: I've added a revised version for the Release Candidate of EF 4.1 below

After some hunting, I've found the answer that works for me:

EF4.1 RC version:

modelBuilder.Entity<Booking>().HasRequired(b => b.Booker)
    .WithMany(m => m.BookedSlots).Map(p=>{
                    p.MapKey("BookerID");
    });

in your case:

modelBuilder.Entity<Sale>().HasRequired(sale => sale.Shop)
    .WithMany().Map(s=> {
           s.MapKey("StoreId");
    });

My version is slightly different because I have navigation properties on both sides of the relationship.

Mark Adamson
  • 878
  • 10
  • 17
2

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

Morteza Manavi
  • 33,026
  • 6
  • 100
  • 83
0

I think what you're looking for is the RelatedTo attribute. More information in this ADO.NET team blog post.

AJ.
  • 16,368
  • 20
  • 95
  • 150