问题描述
现有的数据库架构具有唯一的非主键和一些依赖于它们的外键.
An existing DB schema has unique, non-primary, keys, and some foreign keys that rely on them.
是否可以在实体框架 v4 中定义非主键的唯一键?怎么样?
Is it possible to define unique keys, which are not primary keys, in Entity Framework v4? How?
推荐答案
我尝试定义以下表格:
- 订单 [Id (primary, identity), ClientName, FriendlyOrderNum (unique)]
- OrderItems [Id (primary, identity), FriendlyOrderNum (unique), ItemName]
以及从 OrderItems.FriendlyOrderNum (Mant) 到 Orders.FriendlyOrderNum (one) 的外键映射.
And a foreign key mapping from OrderItems.FriendlyOrderNum (Mant) to Orders.FriendlyOrderNum (one).
如果唯一的非主键是可能的,那么以下 SSDL 应该可以工作:
If unique non-primary keys are possible the following SSDL should work:
<Schema Namespace="EfUkFk_DbModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl">
<EntityContainer Name="EfUkFk_DbModelStoreContainer">
<EntitySet Name="OrderItems" EntityType="EfUkFk_DbModel.Store.OrderItems" store:Type="Tables" Schema="dbo" />
<EntitySet Name="Orders" EntityType="EfUkFk_DbModel.Store.Orders" store:Type="Tables" Schema="dbo" />
</EntityContainer>
<EntityType Name="OrderItems">
<Key>
<PropertyRef Name="RowId" />
</Key>
<Property Name="RowId" Type="bigint" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="OrderNum" Type="char" Nullable="false" MaxLength="5" />
<Property Name="ItemName" Type="varchar" MaxLength="100" />
</EntityType>
<!--Errors Found During Generation:
warning 6035: The relationship 'FK_OrderItems_Orders' has columns that are not part of the key of the table on the primary side of the relationship. The relationship was excluded.
-->
<EntityType Name="Orders">
<Key>
<PropertyRef Name="RowId" />
</Key>
<Property Name="RowId" Type="bigint" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="ClientName" Type="varchar" MaxLength="100" />
<Property Name="OrderNum" Type="char" Nullable="false" MaxLength="5" />
</EntityType>
<!-- AsafR -->
<Association Name="FK_OrderItems_Orders">
<End Role="Orders" Type="EfUkFk_DbModel.Store.Orders" Multiplicity="1">
</End>
<End Role="OrderItems" Type="EfUkFk_DbModel.Store.OrderItems" Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="Orders">
<PropertyRef Name="OrderNum" />
</Principal>
<Dependent Role="OrderItems">
<PropertyRef Name="OrderNum" />
</Dependent>
</ReferentialConstraint>
</Association>
</Schema></edmx:StorageModels>
它没有.也没有可能添加更多 <key>.
It doesn't. There's also no possibility for adding more <key> elements in an <EntityType>.
我的结论是 EF 4 不支持非主唯一键.
My conclusion is that non-primary unique keys are not support in EF 4.
这篇关于实体框架 4 中的唯一键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!