Dofactory.com
Dofactory.com
 Back to list
Views:   10.5K
Replies:  2
Archived

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,

Mark
Mark Pow, Feb 18, 2013
Reply 1
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,

Mark
Mark Pow, Feb 26, 2013
Reply 2
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 
Isaiah Nelson, Feb 19, 2013
Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.