5

I am using Entity Framework Database First, but I would like to replicate the following behavior from the Code First paradigm:

In Entity Framework Code First, you can do something along these lines:

public class Thing
{
    public int ID { get; set; }
    ICollection<Stuff> Stuffs { get; set; }
}

public class Stuff
{
    public int ID { get; set; }
    ICollection<Thing> Things { get; set; }
}

And the database will generate and Associative table to represent the many to many relationship.

I'm using Database First with a legacy database. I pulled in the entities and it included the associative table representing a many-to-many relationship between two of our tables.

Since the associative table is included as an entity, the navigation properties are as such:

public class Thing
{
    public int ID { get; set; }
    public ICollection<ThingStuff> ThingStuffs { get; set; }
}

public class ThingStuff
{
    public int ThingID { get; set; }
    public int StuffID { get; set; }
    ICollection<Thing> Things { get; set; }
    ICollection<Stuff> Stuffs { get; set; }
}

public class Stuff
{
    public int ID { get; set; }
    public ICollection<ThingStuff> ThingStuffs { get; set; }
}

So to navigate, I have to:

var stuff = Thing.ThingStuffs.Select(ts => ts.Stuff);

Instead of:

var stuff = Thing.Stuffs;

So The Question Is:

Is there any way to drop the entity representing the association (ThingStuff) and tell EntityFramework about the existing table to create the many-to-many navigation properties?

Michael
  • 1,535
  • 2
  • 17
  • 32
  • 1
    I think the real junction table had more attributes than just the two foreign keys, or a separate primary key, otherwise EF wouldn't have incorporated it in the conceptual model. Is that right? – Gert Arnold May 14 '13 at 21:32
  • In addition to what @GertArnold said if one of the foreign keys is nullable then EF database first also includes the associated table as a separate entity. –  May 15 '13 at 01:14

1 Answers1

0

Wouldn't it be better if you map your composite keys, as stated in the fluent api documentation? http://msdn.microsoft.com/en-us/data/jj591617.aspx