EF 映射到实体上的错误键



当我运行linq查询时,它试图将SchoolInfo.SchoolInfoId映射到SchoolId.SchoolId。

如何定义正确的映射,以便它知道将SchoolInfo.SchoolId映射到School.SchoolId?

这是代码优先。

SQL 表

table School
(
    int SchoolId not null PK
)
table SchoolInfo
(
    int SchoolInfoId not null PK
    int SchoolId not null FK
)

模型

class School
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    int schoolId;
    virtual SchoolInfo SchoolInfo;
}
class SchoolInfo
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    int schoolInfoId;
    int schoolId;
    virtual School School
}
modelBuilder.Entity<School>().HasOptional(a => a.SchoolInfo).WithRequired(a => a.School);

更合适的方法是:

数据库:

TABLE School (
    INT SchoolId NOT NULL PK
)
TABLE SchoolInfo (
    INT SchoolId NOT NULL PK -- FK
)

学校模式:

public class School
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int schoolId { get; set; }
    public virtual SchoolInfo SchoolInfo { get; set; }
}

学校信息模型选项 1:

public class SchoolInfo
{
    [Key, ForeignKey("School")]
    public int schoolId { get; set; }
    public virtual School School { get; set; }
}

学校信息模型选项 2:

public class SchoolInfo
{
    [ForeignKey("School")]
    public int SchoolInfoId { get; set; }
    public virtual School School { get; set; }
}

学校信息模型选项 3:

public class SchoolInfo
{
    [Key]
    public int schoolId { get; set; }
    public virtual School School { get; set; }
}
// Relationship:
modelBuilder.Entity<School>().HasOptional(a => a.SchoolInfo).WithRequired(a => a.School);

由于您提到的限制,另一种方法是:

您的实际数据库:

TABLE School (
    INT SchoolId NOT NULL PK
)
TABLE SchoolInfo (
    INT SchoolInfoId NULL PK
    INT SchoolId NOT NULL FK -- WITH UNIQUE CONSTRAINT TO ENSUERE ONE TO ONE
)

学校模式:

public class School
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int schoolId { get; set; }
    public virtual SchoolInfo SchoolInfo { get; set; }
}

学校信息模型选项 1:

public class SchoolInfo
{
    public int schoolInfoId { get; set; }
    [Key]
    public int schoolId { get; set; }
    public virtual School School { get; set; }
}
// Relationship:
modelBuilder.Entity<School>().HasOptional(a => a.SchoolInfo).WithRequired(a => a.School);

学校信息模型选项 2(我没有测试它):

public class SchoolInfo
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int schoolInfoId { get; set; }
    [ForeignKey("School")]
    public int schoolId { get; set; }
    public virtual School School { get; set; }
}
// Relationship:
modelBuilder.Entity<School>().HasOptional(a => a.SchoolInfo).WithRequired(a => a.School);

你可以看到:

http://www.entityframeworktutorial.net/entity-relationships.aspxhttp://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

最新更新