实体框架和外键:( [英] Having serious problems with Entity Framework & Foreign Keys :(

本文介绍了实体框架和外键:(的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的EDMX中有以下实体: -



这两个内容是由更新模型从数据库生成的。



现在,注意我的国家/地区具有以下主键: -



名称& IsoCode



这是因为系统中的每个国家都是UNIQUE,由Name和IsoCode组成。



现在,我的国家...这是相似的。主键是: -



名称& CountryId



每个州名称和国家/地区都是唯一的。



国家的外键是国家。这是sql: -

  ALTER TABLE [dbo]。[States] WITH CHECK ADD 
CONSTRAINT [FK_States_Countries] FOREIGN KEY([CountryId])
参考文献[dbo]。[Countries]([CountryId])
更新CASCADE
GO

ALTER TABLE [dbo]。 [状态]检查约束[FK_States_Countries]
GO

很简单的东西。



但是EntityFramework不喜欢它:(假设我需要将一些属性从 State 实体连接到主键属性在国家/地区实体中。



是否可以在国家/地区之间添加一个协会。 CountryId< - > State.CountryId ...像我已经映射到我的数据库?



干杯;)

解决方案

在EF(3.5和4.0)中,FK必须指向主键。



但是你似乎是试图指出候选关键字(即[国家]] [我知道这是EF团队正在考虑的下一个版本,但是:)



希望这有助于



Alex


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 :-

Name & 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 :-

Name & CountryId

Each state is unique by name and per country.

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

Pretty simple stuff.

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.

Is it possible to add an ASSOCIATION between Country and State on Country.CountryId <-> State.CountryId ... like i have mapped in my DB ?

Cheers ;)

解决方案

In EF (3.5 and 4.0) FKs MUST point to Primary Keys.

But you appear to be attempting to point to a Candidate Key (i.e. [Countries].[CountryId]

I know that this is something the EF team are considering for the next version though :)

Hope this helps

Alex

这篇关于实体框架和外键:(的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆