我的數據模型包含兩個包含複合主鍵和關聯表的表。組合主鍵的一部分在表格之間是通用的。在Entity Framework中,如何使用主鍵的子集創建引用約束?
SitePrivilege
-------------
SiteId
PrivilegeId
UserSite
--------
SiteId
UserId
UserSitePrivilege
-----------------
UserId
SiteId
PrivilegeId
我已經創建了一個SitePrivilege實體和一個UserSite實體。我已經將它們之間的多對多關聯映射到UserSitePrivilege。
<Association Name="UserSiteSitePrivilege">
<End Type="PrivilegeModel.UserSite" Multiplicity="*" Role="UserSite" />
<End Type="PrivilegeModel.SitePrivilege" Multiplicity="*" Role="SitePrivilege" />
</Association>
...
<AssociationSetMapping Name="UserSiteSitePrivilege" TypeName="PrivilegeModel.UserSiteSitePrivilege" StoreEntitySet="UserSitePrivilege">
<EndProperty Name="SitePrivilege">
<ScalarProperty Name="PrivilegeId" ColumnName="PrivilegeId" />
<ScalarProperty Name="SiteId" ColumnName="SiteId" />
</EndProperty>
<EndProperty Name="UserSite">
<ScalarProperty Name="SiteId" ColumnName="SiteId" />
<ScalarProperty Name="UserId" ColumnName="UserId" />
</EndProperty>
</AssociationSetMapping>
以上代碼生成此錯誤:
Each of the following columns in table UserSitePrivilege is mapped to multiple conceptual side properties: UserSitePrivilege.SiteId is mapped to UserSiteSitePrivilegeSitePrivilege.SiteId, UserSiteSitePrivilege.UserSite.SiteId
所以我添加參考約束。
<Association Name="UserSiteSitePrivilege">
<End Type="PrivilegeModel.UserSite" Multiplicity="*" Role="UserSite" />
<End Type="PrivilegeModel.SitePrivilege" Multiplicity="*" Role="SitePrivilege" />
<ReferentialConstraint>
<Principal Role="UserSite">
<PropertyRef Name="SiteId"/>
</Principal>
<Dependent Role="SitePrivilege">
<PropertyRef Name="SiteId"/>
</Dependent>
</ReferentialConstraint>
</Association>
...
<AssociationSetMapping Name="UserSiteSitePrivilege" TypeName="PrivilegeModel.UserSiteSitePrivilege" StoreEntitySet="UserSitePrivilege">
<EndProperty Name="SitePrivilege">
<ScalarProperty Name="PrivilegeId" ColumnName="PrivilegeId" />
<ScalarProperty Name="SiteId" ColumnName="SiteId" />
</EndProperty>
<EndProperty Name="UserSite">
<ScalarProperty Name="SiteId" ColumnName="SiteId" />
<ScalarProperty Name="UserId" ColumnName="UserId" />
</EndProperty>
</AssociationSetMapping>
現在,它會產生這樣的錯誤:
Properties referred by the Principal Role UserSite must be exactly identical to the key of the EntityType PrivilegeModel.UserSite referred to by the Principal Role in the relationship constraint for Relationship PrivilegeModel.UserSiteSitePrivilege. Make sure all the key properties are specified in the Principal Role.
如何正確模擬這種關係?
整個複合鍵在外鍵中使用。 UserSitePrivilege有兩個複合外鍵:(UserId,SiteId)和(SiteId,PrivilegeId)。但由於它是一個關聯表,它並不表示爲一個實體。 任一表上的代理主鍵都能解決問題,但我希望我不必要求DBA改變DB設計來滿足EF。他的設計是有效的。 – 2009-06-17 22:30:23