EF映射到实体上的错误键

时间:2016-05-20 14:52:42

标签: c# sql .net entity-framework fluent

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

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

这是Code-First。

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

1 个答案:

答案 0 :(得分:2)

更合适的方法是:

数据库:

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 Model Option 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