EF Core 1.0 Foreign Key Issue

entity-framework entity-framework-core

Question

I do not really understand is this EF Core 1.0 bug?

public class User : BaseEntity
{
    public string Username { get; set; }
}
public class UserDetail : BaseEntity
{
    public int UserId { get; set; }
    public string Address { get; set; }
    public string Country { get; set; }

    public virtual User User { get; set; }

    [ForeignKey("UserId")]
    public virtual ICollection<UserLanguage> Languages { get; set; }
}

public class UserLanguage : BaseEntity
{
    public string Name { get; set; }
    public int UserId { get; set; }
}

In my User table I have 3 users

Id          Username
----------- ---------------

1           john
2           doe
3           jack

In my UserDetail I have 2 records

Id          UserId      Address                                           Country
----------- ----------- -------------------------------------------------- ------
1           1           Some Address                                       MY
2           3           NULL                                               SG

In my UserLanguage when perform insert

INSERT INTO UserLanguage(Name, UserId)
VALUES ('English', 3) 

it will encounter below error

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_UserLanguage_UserDetail_UserId". The conflict occurred in database "Job", table "dbo.UserDetail", column 'Id'.

What I do wrong in here? ForeignKey is UserId how come it point to UserDetail column 'Id'

Accepted Answer

try the following

public class User : BaseEntity
{
    public string Username { get; set; }

    public virtual ICollection<UserLanguage> Languages { get; set; }
}
public class UserDetail : BaseEntity
{
    public int UserId { get; set; }
    public string Address { get; set; }
    public string Country { get; set; }

    public virtual User User { get; set; }        
}

public class UserLanguage : BaseEntity
{
    public string Name { get; set; }
    public int UserId { get; set; }

    public virtual User User { get; set; } 
}

The problem was in the following line of code

[ForeignKey("UserId")]
public virtual ICollection<UserLanguage> Languages { get; set; }

this created a foreign key relation between UserDetail and UserLanguage table while you wanted to create it between User and UserLanguage table.

In your existing schema if you try to insert

INSERT INTO UserLanguage(Name, UserId)
VALUES ('English', 1) 
INSERT INTO UserLanguage(Name, UserId)
VALUES ('French', 2) 

It will succeed as UserDetail have two entries with 1,2 PK while there is no entry with PK 3 in UserDetail.


Popular Answer

To your UserLanguage class try to add:

public virtual UserDetail UserDetail  { get; set; }


Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why