Entity Framework 4 - Designing DB To Enforce Multiplicity of 1 to 1

466 views Asked by At

I have encountered a scenario in my application where I would like to have a 1:1 multiplicity between entities but I dont know how to modify my database to ensure this.

Lets say I have a Document table and an Index table where the Document will always have one Index and the Index will only ever be contained in one Document. In the Document table I had an IndexID field so the Document entity has a navigation property to its index, but the Index entity has a collection navigation property called Documents, which is not what I am after since there will only ever be one related Document.

It would be nice to edit my DB schema somehow so that when I generate the model from the DB, the Document entity has a single navigation to Index AND the Index has a single navigation property back to the Document. Is such a thing possible?

I figured I could probably edit the entity model or its associations in the model design surface to make this happen. But I am concerned that at some stage if I reload the model, it will reset this and any others like it.

Is there an elegant solution to make EF automatically realize there is a 1:1 multiplicity?

Thanks for any advice!

1

There are 1 answers

0
Ladislav Mrnka On BEST ANSWER

Your database does not model 1:1 relationship between Document and Index and so EF doesn't model it as well. To use 1:1 your Document and Index has to share primary key. It means that you will define Document with some PK (probably autogenerated) and you will define Index with PK of same type and you will also define FK where PKs from both sides will participate. This will enforce 1:0..1 relation between Document and Index. 0..1 is because you always need to insert Document first and after that you need to insert Index (document will live without Index for fraction of second). It is your application logic responsibility to enforce that Document will be always inserted together with Index.