EF5 one-to-one without navigation

你。 提交于 2019-12-02 12:04:47

OK, so i have copied your code and tried it and my answer has multiple parts:

  1. With your current configuration the generated database is messed up some how, see in the Users table the "UserId" is becoming the FK (i don't know why really) so "RankId" is just becoming a normal integer property (it is not a key), so i think this is what triggers the first exception you mentioned about the ReferentialConstraint, because if you think about it, the database knows that "UserId" is a primary key, and at the same time it is a foreign key but the actual key that is referenced by "UserId" which is "RankId" is not database generated so how is the database suppose to figure out all of this information.
  2. Now there might be a "right configuration to fix this but i couldn't find, so to solve this i removed the fluent configurations and Entity Framework created everything by convention and it did a great job (it figured out that "RankId" in the User class is actually a foreign key).

An advice, try to see what's wrong with the configuration and with every change you make use SQL Server Management Studio or any other tool you have to check out the generated database schema to be sure it is what you wish it to be, plus if you don't need the configuration just don't use it.

phil soady

1:1 code first in EF requires the dependent table to have the SAME primary key. Otherwise what you want to do will work.

EDIT Similar SO post Code First and Fluent API one to one relationship

Here is the MS EF site sample. http://msdn.microsoft.com/en-us/data/jj591620#RequiredToRequired

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