EF4.1: Possible to have zero-or-one to zero-or-one (0..1 to 0..1) relationship?

前端 未结 3 663
轮回少年
轮回少年 2021-01-14 10:41

.NET 4.0 with SQL Server 2008 R2. I am trying to represent a 0..1 to 0..1 relationship and I keep getting the following error:

Error 113: Multiplicit

3条回答
  •  时光说笑
    2021-01-14 11:14

    No it is not possible and I doubt it works in SQL server. Database relation requires that one end becomes dependent. It means that it references primary key (PK) of a principal end - we call this foreign key (FK). If we talk about one-to-one relation the FK must be marked as unique so that only one record in the dependent table can reference a given record from the principal table. The only valid relation in this case is 0..1 - 1 where principal can exist without dependent but the dependent can exist only when related to existing principal because its FK value must be set to PK value of the principal. Theoretically FK can be nullable but it depends on the way how database implements unique constraints. If the database counts null as another unique value only one dependent record can have FK set to null (I think this is a case of SQL server).

    In EF this is even more complicated because EF doesn't support unique constraints and because of that you can build one-to-one relation only when FK in dependent entity is also its PK (= no way to set it to null). If you cannot set FK to null you cannot have it nullable and because of that principal entity must exists otherwise the referential integrity will throw error.

    The best solution for you is considering Request as principal entity and Result as dependent. Request must be created first and it must be kept in the database as long as the Result. Result must have same PK value (the column cannot be auto incremented) as the corresponding Request (and PK must be FK to Request).

提交回复
热议问题