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'
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.
在您的UserLanguage
类中尝试添加:
public virtual UserDetail UserDetail { get; set; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.