Entity Framework Is it possible to add an ASSOCIATION between Primary Keys and a Foreign Key

北城以北 提交于 2019-12-30 09:06:09

问题


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 ;)


回答1:


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




回答2:


For proper DB normalization, first thing is that primary keys must be only CountryId and StateId fields - the main Id fields for each table.

And ss I see from the description Name & IsoCode and Name & CountryId should be actually Unique keys, not primary.

Then the model class State should have a field:

public Country Country { get; set; }

Now EF have very good examples and since 4.3.1 + it fully supports Code first / DB first models, which I think will ease solving this. EF 5 have more compatibility updates so I think it wont be a problem for legacy DB engines.



来源:https://stackoverflow.com/questions/3714334/entity-framework-is-it-possible-to-add-an-association-between-primary-keys-and-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!