EF Core 1.0外键问题

时间:2016-02-01 14:03:22

标签: 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'

2 个答案:

答案 0 :(得分:2)

尝试以下

IEnumerable<Type>

问题出现在以下代码行中

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

这会在UserDetail和UserLanguage表之间创建一个外键关系,而你想在User和UserLanguage表之间创建它。

如果您尝试插入

,则在现有架构中
[ForeignKey("UserId")]
public virtual ICollection<UserLanguage> Languages { get; set; }

它会成功,因为UserDetail有两个带有1,2 PK的条目,而在UserDetail中没有带有PK 3的条目。

答案 1 :(得分:0)

UserLanguage班级尝试添加:

public virtual UserDetail UserDetail  { get; set; }