这是可能的,但它需要在 EDMX 文件中进行大量手动工作,而且我无法让 EF 使用代理键作为链接表上的实际主键。您必须让 EF 使用 foo_id 和 bar_id 的组合键作为主键。
在您的存储模型中,您必须将链接表的 EntityType 从
<EntityType Name="foo_bar">
<Key>
<PropertyRef Name="surrogate_pk" />
</Key>
<Property Name="surrogate_pk" Type="bigint" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="foo_id" Type="int" Nullable="false" StoreGeneratedPattern="None" />
<Property Name="bar_id" Type="int" Nullable="false" StoreGeneratedPattern="None" />
</EntityType>
到:
<EntityType Name="foo_bar">
<Key>
<PropertyRef Name="foo_id" />
<PropertyRef Name="bar_id" />
</Key>
<Property Name="foo_id" Type="int" Nullable="false" StoreGeneratedPattern="None" />
<Property Name="bar_id" Type="int" Nullable="false" StoreGeneratedPattern="None" />
</EntityType>
因此,您使代理键对 EF 不可见,并告诉它使用两个外键的组合作为主键。
在您的概念模型中,您需要定义多对多关联:
<Association Name="foo_bar_association">
<End Role="foo" Type="foo" Multiplicity="*" />
<End Role="bar" Type="bar" Multiplicity="*" />
</Association>
在您的映射中,AssociationSetMapping:
<AssociationSetMapping Name="foo_bar_association" TypeName="foo_bar_association" StoreEntitySet="foo_bar">
<EndProperty Name="foo">
<ScalarProperty Name="id" ColumnName="foo_id" />
</EndProperty>
<EndProperty Name="bar">
<ScalarProperty Name="id" ColumnName="bar_id" />
</EndProperty>
</AssociationSetMapping>
到目前为止,最简单的方法是从数据库中删除代理键,生成 EDMX,然后将此模型放在原始数据库中。结果将是相同的。EF 并不需要任何东西的代理键,该表在多对多关联中是不可见的