EF Core 1.0外鍵問題

entity-framework entity-framework-core

我真的不明白這個EF Core 1.0的錯誤?

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

在我的用戶表中,我有3個用戶

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

1           john
2           doe
3           jack

在我的UserDetail中,我有2條記錄

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

在我的UserLanguage執行插入時

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

它會遇到以下錯誤

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

我在這裡做錯了什麼? ForeignKey是UserId怎麼指向UserDetail列'Id'

一般承認的答案

嘗試以下方法

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

問題出現在以下代碼行中

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

這在UserDetail和UserLanguage表之間創建了一個外鍵關係,而您想在User和UserLanguage表之間創建它。

在您現有的架構中,如果您嘗試插入

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

它將成功,因為UserDetail有兩個帶有1,2 PK的條目,而在UserDetail中沒有帶有PK 3的條目。


熱門答案

UserLanguage類嘗試添加:

public virtual UserDetail UserDetail  { get; set; }


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow