4

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

does not seem to get this going. All I could find up to now was some fluent option, but I'd like to do this with annotations only.

To clarify: I am searching for a DataAnnotation way to create a table with a primary key consisting of 2 fields Id and Nr...

Thanks for your help Andreas

nttakr
  • 1,637
  • 15
  • 25

2 Answers2

10

You can easily do this as follows using Fluent API:

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

Also, you can create separate class that inherit from EntityTypeConfiguration and add this line in its constructor:

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

      public <*Name*>Mapping(){
             this.HasKey(obj => new {obj.Id,obj.Nr});
      }
}
Flexo
  • 87,323
  • 22
  • 191
  • 272
Memo
  • 329
  • 3
  • 5
0

I asked a similar question last week but was looking for the fluent syntax. The answer provided by Morteza (search for more of his answers regarding anything ef/CTP5- he is awesome) also gives the syntax for using data annotations.

Here is the link. Hope this helps.

Community
  • 1
  • 1
trevorc
  • 3,023
  • 4
  • 31
  • 49