Bruce Suitt
Bruce Suitt

Reputation: 11

Using Entity Framework 4.1 Code First Fluent API to configure an Entity that has a composite key based on two other entities

I've just started to get a grasp of Entity Framework and have had no problems with the mapping of simple entities to their individual tables, but now I've run across a more advance scenario that has me stumped.

I have the following POCOs

public class Group  
{  
    public int GroupId  {get; set;}  
    public string GroupName {get; set;}
    public virtual ICollection<EventTypePreference> Preferences {get; set;}
}

public class EventType
{
    public int EventTypeId {get; set;}
    public string EventTypeName {get; set;}
    public string EventColor {get; set;}
}

public class EventTypePreference
{
    public int GroupId {get; set;}
    public int EventTypeId {get; set;}

    public virtual Group Group {get; set;}
    public virtual EventType EventType {get; set;}
    public int EventLength {get; set;}
}

In my model a Group will have many EventTypePreferences (one preference record for each EventType). EventTypePreferences is a table in the database with the same matching columns as it's corresponding POCO. Also, in the database the EventTypePreference table uses a composite primary key that is based on the GroupId and the EventTypeId.

So say the Group table has the following rows (GroupId, GroupName)...

1, Human Resources
2, Purchasing
3, Information Services  

And the EventType table has the following rows (EventTypeId, EventTypeName, EventColor)...

1, Training Event, Blue
2, Sales Seminar, Red
3, Office Party, Yellow

The EventTypePreferences would have values as (EventTypeId, GroupId, EventLength)...

1, 1, 60
1, 2, 45
1, 3, 60
2, 1, 120
.........

My problem is that I am struggling to figure out how to fluently configure these relationships particularly for my EventTypePreference entity. I'm seeing it as there are many Groups and EventTypes in this entity. Can someone help shed some light to this for me?

Upvotes: 1

Views: 2127

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364399

Try this:

modelBuilder.Entity<EventTypePreference>()
            .HasKey(p => new { p.EventTypeId, p.GroupId });

modelBuilder.Entity<EventTypePreference>()
            .HasRequired(p => p.EventType)
            .WithMany()
            .HasForeignKey(p => p.EventTypeId);

modelBuilder.Entity<EventTypePreference>()
            .HasRequired(p => p.Group)
            .WithMany(g => g.Preferences)
            .HasForeignKey(p => p.GroupId);

Upvotes: 8

Related Questions