问题
I'm using Entity Framework 4.1 database first approach. I've used legacy database. In my edmx file which created entity classes based on tables in the legacy database, there is a one-to-zero-or-one association between some entities.
Although I explored the tables of database and relation between them I didn't find out how one-to-zero-or-one relation have been implemented in database.
For more information I put some screenshots of my database diagram and the property of its relation and correspondent entities in edmx file:
回答1:
The 1-0..1 relation in your database is directly visible. It is built between Course and OnlineCourse tables where Course is principal in relation (1) and OnlineCourse is dependent with FK configured on CourseID. FK is also PK of the OnlineCourse = it must be unique and because of that it is 0..1.
Database "always" uses 1 - 0..1 because real 1 - 1 cannot be effectively used for data insertion. 1 - 1 means that left must be inserted after right but right must be inserted after left = impossible. Because of that 1 - 0..1 is used where left is principal and must be inserted before right and right is dependent and must be inserted after left.
回答2:
If the database tables are already designed with a 1:1 relationship (or a 1:0-1), then EF will work with it just fine, although it will pluralize the child table's name (if you let it pluralize).
The basic approach is to create a foreign key (as if you were making a 1:many relationship), then put a unique index on the foreign key field. Is that what you are aiming to accomplish?
This might help, too: Designing 1:1 and 1:m relationships in SQL Server .
On a side note, 1-1 relationships are often not necessary and/or a symptom of a database design that needs rethinking. However, it sounds like you inherited the design... I know all about that!
来源:https://stackoverflow.com/questions/7644156/implementing-one-to-zero-or-one-relation-in-sql-server