Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Multiple Column as Primary Key by Fluent Api

These are my simplified domain classes.

public class ProductCategory {     public int ProductId { get; set; }     public int CategoryId { get; set; }      public virtual Product Product { get; set; }     public virtual Category Category { get; set; } }  public class Product {     public int Id { get; set; }     public string Name { get; set; } }   public class Category {     public int Id { get; set; }     public string Name { get; set; }     public int? ParentCategoryId { get; set;}  }  

This is my mapping class. But it doesn't work.

public class ProductCategoryMap : EntityTypeConfiguration<ProductCategory> {     public ProductCategoryMap()     {         ToTable("ProductCategory");         HasKey(pc => pc.ProductId);         HasKey(pc => pc.CategoryId);     } } 

How should I map these classes to provide, so that one product can be seen in multiple categories?

like image 731
Barış Velioğlu Avatar asked Mar 16 '13 21:03

Barış Velioğlu


People also ask

How do you configure a primary key for an entity in Entity Framework Fluent API?

Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.

How do I add a composite primary key in Fluent API?

The only way to configure composite keys is to use the HasKey method. You specify the properties that form the composite key by passing them in as properties of an anonymous type to the HasKey method.

Does data annotation attributes override Fluent API configuration?

Data annotations and the fluent API can be used together, but Code First gives precedence to Fluent API > data annotations > default conventions. Fluent API is another way to configure your domain classes.

What is HasKey?

HasKey is a Fluent API method, which allows us to configure the primary key & composite primary of an entity in EF Core.


1 Answers

Use anonymous type object instead of 2 separated statements:

HasKey(pc => new { pc.ProductId, pc.CategoryId }); 

From Microsoft Docs: EntityTypeConfiguration.HasKey Method

If the primary key is made up of multiple properties then specify an anonymous type including the properties. For example, in C# t => new { t.Id1, t.Id2 } and in Visual Basic .Net Function(t) New With { t.Id1, t.Id2 }.

like image 72
MarcinJuraszek Avatar answered Sep 20 '22 01:09

MarcinJuraszek