EF 映射到实体上的错误键

EF is mapping to the wrong keys on entities

当我 运行 一个 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; }
}

SchoolInfo 模型选项 1:

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

    public virtual School School { get; set; }
}

SchoolInfo 模型选项 2:

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

    public virtual School School { get; set; }
}

SchoolInfo 模型选项 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; }
}

SchoolInfo 模型选项 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);

SchoolInfo 模型选项 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.aspx http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx