实体框架是否可以在主键和外键之间添加关联 [英] Entity Framework Is it possible to add an ASSOCIATION between Primary Keys and a Foreign Key
问题描述
我的EDMX上有以下实体:-
I've got the following entities on my EDMX :-
这两个实体是由从数据库更新模型生成的.
These two entites were generated by Update Model From Database.
现在,请注意我国是如何具有以下主键的:-
Now, notice how my country has the following primary key :-
名称& IsoCode
这是因为按名称和IsoCode,每个国家/地区在系统中都是唯一的.
this is because each country is UNIQUE in the system by Name and IsoCode.
现在,与我的国家...相似.主键是:-
Now, with my States ... it's similar. Primary Key is :-
名称& CountryId
每个州在名称和国家/地区上都是唯一的.
Each state is unique by name and per country.
现在,国家/地区的外键是一个CountryId.这是sql:-
Now, the Foreign Key for States is a CountryId. This is the sql :-
ALTER TABLE [dbo].[States] WITH CHECK ADD
CONSTRAINT [FK_States_Countries] FOREIGN KEY([CountryId])
REFERENCES [dbo].[Countries] ([CountryId])
ON UPDATE CASCADE
GO
ALTER TABLE [dbo].[States] CHECK CONSTRAINT [FK_States_Countries]
GO
非常简单的东西.
但是EntityFramework不喜欢它:(假设我需要将State
实体的某些属性连接到Country
实体的两个主键属性.
BUT EntityFramework doesn't like it :( It's assuming that i need to connect some properties from State
entity to both primary key properties in the Country
entity.
是否可以在Country.CountryId<-> State.CountryId ...上添加Country和State之间的关联,就像我已经映射到数据库中一样?
干杯;)
推荐答案
在EF(3.5和4.0)中,FK必须指向主键.
In EF (3.5 and 4.0) FKs MUST point to Primary Keys.
但是您似乎正在尝试指向候选关键字(即[Countries].[CountryId]
But you appear to be attempting to point to a Candidate Key (i.e. [Countries].[CountryId]
我知道这是EF团队正在考虑的下一个版本:)
I know that this is something the EF team are considering for the next version though :)
希望这会有所帮助
亚历克斯
这篇关于实体框架是否可以在主键和外键之间添加关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!