1

Entity Framework 神奇地将下表结构解释为多对多关系。

table foo (int id)
table foo_bar (int foo_id, int bar_id)
table bar (int id)

但是如果连接表有任何附加字段,它将被解释为两个一对多的关系。

我正在使用一个数据库,其中连接表有一个代理键作为主键。因此,EF 将其解释为两个一对多的关系。

table foo (int id)
table foo_bar (int surrogate_pk, int foo_id, int bar_id)
table bar (int id)

是否可以修改 EF:s 解释以使其成为模型中实际的多对多关系?可以使用设计器完成吗?

4

2 回答 2

2

这是可能的,但它需要在 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 并不需要任何东西的代理键,该表在多对多关联中是不可见的

于 2011-01-04T20:15:59.253 回答
1

我很肯定这不能使用设计器来完成。我不知道是否有办法在 EDMX 中手动执行此操作,但我从未见过它的示例。一种可能的解决方法可能是根本不映射代理键。如果您可以在数据库上生成它,那么您的模型中可能不需要它。

于 2009-02-16T20:47:47.280 回答