2009-02-16 102 views
1

实体框架神奇地将下表结构解释为多对多关系。实体框架中与代理键的多对多关系

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解释使其成为模型中的实际多对多关系?可以使用设计师来完成吗?

回答

1

我认为这不能用设计师来完成。我不知道是否有办法在EDMX中手动完成它,但我从未见过它的例子。一种可能的解决方法可能是根本不映射代理键。如果你可以在数据库上生成它,你可能不需要在你的模型中使用它。

+0

代理键没有真正的兴趣,所以这将很好地工作。从模型中删除字段似乎没有任何区别。它可以被排除在一个更确定的方式或东西? – 2009-02-16 20:55:42

+0

在设计器中删除代理键不会将其从存储模型中删除。你必须手动编辑EDMX。 – 2009-02-16 21:29:16

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并不需要任何代理键,这个表在多关联中是不可见的