views:

20

answers:

1

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.

A: 

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; }
Gary Clarke

related questions