The Entity Framework recognizes that ProductId is the foreign key property for the Product navigation property, and SpecificationId is the foreign key property for the Specification navigation property. But the exception complains about the missing primary key ("Key" = "Primary Key") on your ProductSpecification object. Each object requires a specific key property. This can happen either by agreement - by the specific name of the key property, or by simplicity with data annotations or the Fluent API.
Your ProductSpecification class does not have a property that EF recognizes as a key by convention: No Id property and no ProductSpecificationId (class name + "Id").
Therefore, you must define this explicitly. Defining it with data annotations is shown in the message you linked:
public class ProductSpecification { [Key, Column(Order = 0)] public int ProductId { get; set; } public virtual Product Product { get; set; } [Key, Column(Order = 1)] public int SpecificationId { get; set; } public virtual Specification Specification { get; set; } public string SpecificationValue { get; set; } }
And in the Fluent API, it will be:
modelBuilder.Entity<ProductSpecification>() .HasKey(ps => new { ps.ProductId, ps.SpecificationId });
Both methods define a composite key, and each part is a foreign key in the Product or Specification table at the same time. (You do not need to explicitly define the properties of FK because EF recognizes it because of its conditional names.)
You can return the product, including all specifications, with a downloaded download, for example:
var product = db.Products .Include(p => p.ProductSpecifications.Select(ps => ps.Specification)) .SingleOrDefault(x => x.Id == id);
source share