Home  /  Questions  /  Question

50   50
Feb 18, 2013

Entity Framework, Composite Meaningful keys and the Identiy Field pattern

I'm working with a database which uses composite, meaningful, natural keys. Some tables use two columns to create the primary key and some use three and they are all used to define the relationships between the tables.

What is the best way to handle these types of key? If I create a separate "CompoundKey" class in the Data Layer how would I use it in the POCO classes and for querying?

Any suggestions would be greatly appreciated - I'm fairly reluctant to change the DB schema but if there are clear advantages then I, of course, will!

Kind regards,


50   50
Feb 19, 2013
Mark, since responses are dead slow around here on this forum, I will take a shot at answering your question. Regarding composite keys in Code First or Code First with an Existing Database (as I suspect you are doing), then you can seed the properties you are using as keys with the [Key] attribute much in the same way you would with a single key (e.g. UserId). In your case, however, you will need to seed each key as:
[Key, Column(Order = 0)]
public Int UserId {get; set;}

[Key, Column(Order = 1)]
public String VinNumber {get; set;}

I wouldn't create a CompoundKey class in the Data Layer to handle this. When you already have the ability to form a composite key this way. Hopefully this answers your question. Hope this helps, Isaiah 

50   50
Feb 26, 2013
Many thanks for your time Isaiah. I'll investigate the Code First with an existing database (embarrisingly I didn't realise you could use it with an existing database!) and I'll post back.

Kind regards,


0   0
7 days ago
Just we all have this brawl stars cheats online to have the resources for the game that we love online.