EF5 one-to-one without navigation

后端 未结 2 566
遥遥无期
遥遥无期 2021-01-26 16:35

I\'m trying to do a one-to-one relationship, with the navigation property just on one side (MVC4, EF5, code first).

public class User {

  public int UserId { ge         


        
相关标签:
2条回答
  • 2021-01-26 16:40

    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.

    0 讨论(0)
  • 2021-01-26 17:01

    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

    0 讨论(0)
提交回复
热议问题