Entity Framework Columna Múltiple como Clave Primaria por Fluent Api


Estas son mis clases de dominio simplificadas.

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

Esta es mi clase de asignación. Pero no funciona.

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

¿Cómo debo asignar estas clases para proporcionar, para que un producto se pueda ver en múltiples categorías ?

Author: Sergey Berezovskiy, 2013-03-17

2 answers

Use objetos de tipo anónimo en lugar de 2 sentencias separadas:

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

Desde MSDN: EntityTypeConfiguration.Método HasKey

Si la clave principal está formada por varias propiedades, especifique un tipo anónimo que incluya las propiedades. Por ejemplo, en C # t => new { t.Id1, t.Id2 } y en Visual Basic.Net Function(t) New From { t.Id1, t.Id2 }.

 85
Author: MarcinJuraszek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-16 21:11:28

Frustrantemente, particularmente si resulta que no tiene fluidez en lambda, el ejemplo de MSDN VB es incorrecto... eso debería ser un "Con", no un "De".

(Gracias Aki Siponen )

 0
Author: saminpa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-28 14:08:00