views:

679

answers:

4

I'm getting to grips with EF4 code first, and liking it so far. But I'm having trouble mapping an entity to a table with a composite primary key.

The configuration I've tried looks like this:

public SubscriptionUserConfiguration()

    {
                Property(u => u.SubscriptionID).IsIdentity();
                Property(u => u.UserName).IsIdentity();
    }

Which throws this exception: Unable to infer a key for entity type 'SubscriptionUser'.

What am I missing?

A: 

You have two identities...

BlueRaja - Danny Pflughoeft
Yes, that's my question. Two properties of the entity map to the composite primary key in the database. Is that not possible in EF4?
jamesfm
+1  A: 

Solved it: I should be using HasKey, not Identity. This works:

public SubscriptionUserConfiguration()
{
     HasKey(u => u.SubscriptionID);
     HasKey(u => u.UserName);
}
jamesfm
Or maybe it's necessary to use the form suggested by Daniel? http://stackoverflow.com/questions/3299268/entity-framework-ctp4-and-composite-keysI'm assuming it worked for you fine, though.
Derek Morrison
A: 

You could also use

HasKey(u => new { u.SubscriptionID, u.UserName });

Edit:

One limitation I have found is that the following do not work:

public ProjectAssignmentConfiguration()
{
    HasKey(u => u.Employee.EmployeeId);
    HasKey(u => u.Project.ProjectId);
}

or

public ProjectAssignmentConfiguration()
{
    HasKey(u => new { u.Employee.EmployeeId, u.Project.ProjectId });
}

So how do you set up an entity where the join table has a primary key that is composed of foreign keys?

Daniel Skinner
A: 

But how to develop relationship with multiple property (Composite field). Follwoing syntax support only one property mapping

builder.Entity() .Relationship(p => p.CostCenter) .FromProperty(c => c.ActivityCodes) .HasConstraint((p, c) => p.CostCenterId == c.CostCenterId);

repeating above line for another property , it doesn't work.

samir