2

I am using EF4 code first and want to generate a composite key which is made of a class property and foreign key. I have two classes: Order and Company. The Order class holds a reference but this will not necessarily be unique between companies. So I intend to use a composite key made up of Reference and Company.CompanyId.

I have tried using the following to set it but I get an error message "Key expression is not valid".

modelBuilder.Entity<Order>().HasKey(o => new { o.Reference, o.Company.CompanyId });

I have also tried

modelBuilder.Entity<Order>().HasKey(o => new { o.Reference, o.Company });

and this fails.

these are my classes:

public class Order
{
   public string Reference { get; set; }
   public Company Company { get; set; }
}

public class Company
{
   public int CompanyId { get; set; }
   public virtual ICollection Orders { get; set; }
}

Any help would be greatly appreciated.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
user482833
  • 111
  • 2
  • 8

4 Answers4

5

As Antony Highsky mentioned, you can only use scalar properties in the key. So, you will need to add a foreign key (scalar property) to the Order class and associate it with the navigation property Company as shown below:

public class Order
{
    public string Reference { get; set; }

    public int CompanyId { get; set; }

    [RelatedTo(ForeignKey = "CompanyId")]
    public Company Company { get; set; }
}

And then create the composite key using the model builder:

modelBuilder.Entity<Order>().HasKey(o => new { o.Reference, o.CompanyId }); 

Note that data annotations (RelatedTo attribute) were introduced with the Entity Framework CTP 3. For another option that only uses data annotations instead of HasKey method, see this post:

Luis Rocha
  • 1,369
  • 10
  • 7
1

One thing that doesn't look quite right is your use of the non-generic version of ICollection. Try this:

public virtual ICollection<Order> Orders { get; set; }
gxclarke
  • 1,953
  • 3
  • 21
  • 42
1

Did you try this?

modelBuilder.Entity().HasKey(o =>o.Reference ); modelBuilder.Entity().HasKey(o =>o.CompanyId );

0

According to this source, only scalar properties are allowed in the key. Navigation properties are not.

Antony
  • 1,451
  • 1
  • 12
  • 25