EF Codefirst How to create a key from multiple columns using DataAnnotations

I am trying to get a composite key declared in a class with attributes and DataAnnotation.

[Key]
[Column(Order=1)]
public Guid Id { get; set; }

[Key]
[Column(Order=2)]
public int Nr { get; set; }

doesn't seem to cope. Everything that I could find so far was a pretty good option, but I would like to do this only with annotations.

To clarify: I'm looking for a DataAnnotation method to create a table with a primary key consisting of two fields Id and Nr ...

Thanks for your help Andreas

+3
source share
2 answers

You can easily do this as follows using the Fluent API:

modelBuilder.Entity<YourClass>().HasKey(obj => new {obj.Id,obj.Nr});

In addition, you can create a separate class that inherits from EntityTypeConfigurationand add this line to your constructor:

public class <*Name*>Mapping:EntityTypeConfiguration<*Name*> 

      public <*Name*>Mapping(){
             this.HasKey(obj => new {obj.Id,obj.Nr});
      }
}
+9
source

, . , Morteza ( - ef/CTP5- ) .

. , .

0

Source: https://habr.com/ru/post/1789986/


All Articles