74

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?

Grigory Zhadko
  • 1,484
  • 1
  • 19
  • 33
Barış Velioğlu
  • 5,709
  • 15
  • 59
  • 105

1 Answers1

152

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 }.

Grigory Zhadko
  • 1,484
  • 1
  • 19
  • 33
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • 1
    For me, in VB.NET, it was `Function(t) With { t.Id1, t.id2 }` that did the trick (rather than "From"). – Alicia Feb 27 '20 at 16:48
  • 1
    Is it possible to convert non-primitive value object containing two fields? : `public class MyId { public int CompanyId; public int UserId } ` – zolty13 Jul 29 '20 at 13:14
  • Thanks to you, I learned this usage. Before I searched a lot time but I got nothing about this. By the way, is it called AlternateKey as well? – ilyas varol Dec 04 '21 at 10:59