Mapping in model two fields first key

2

I have a table whose structure is composed of two PK, I want to include it in my model to insert records to it, but I have problems doing this

my question is how do I declare in my model that I have those two fields as pk, I tried that way but it throws error

namespace MvcApp.Models
{
    public class credito_por_factura
    {
        [Key]
        public decimal id_factura { get; set; }
        [Key]
        public decimal id_credito { get; set; }
    }
}
  

ERROR: The composite primary key order can not be determined for the type 'MvcApp.Models.credito_per_factura'. Use the HasKey or ColumnAttribute method to specify the order of the composite primary keys.

NOTE: I am working on the code of another programmer and I do not understand why he defined that structure, I would do it in another way but I can not alter the structure of the tables

    
asked by Andrex_11 05.12.2018 в 17:46
source

1 answer

1

To create a Primary Key composed in EF, you must indicate the order of each column using the annotation Column .

From the documentation:

  

Entity Framework supports composite keys - primary keys that consist of more than one property. For example, you could have a Passport class whose primary key is a combination of PassportNumber and IssuingCountry.

     

In order to use composite keys, the Entity Framework requires that you define the order of the key properties. You can do this using the column annotation to specify an order:

public class Passport
{
    [Key]
    [Column(Order=1)]
    public int PassportNumber { get; set; }
    [Key]
    [Column(Order = 2)]
    public string IssuingCountry { get; set; }
    public DateTime Issued { get; set; }
    public DateTime Expires { get; set; }
}

Link: Data annotations of Code First

    
answered by 05.12.2018 / 17:53
source