问题
When I run a linq query it's trying to map the SchoolInfo.SchoolInfoId to the SchoolId.SchoolId.
How do I define the correct mapping so it knows to map SchoolInfo.SchoolId to School.SchoolId?
This is Code-First.
SQL Tables
table School
(
int SchoolId not null PK
)
table SchoolInfo
(
int SchoolInfoId not null PK
int SchoolId not null FK
)
Models
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:
A more appropriate way to do is something like:
Data Base:
TABLE School (
INT SchoolId NOT NULL PK
)
TABLE SchoolInfo (
INT SchoolId NOT NULL PK -- FK
)
School Model:
public class School
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int schoolId { get; set; }
public virtual SchoolInfo SchoolInfo { get; set; }
}
SchoolInfo Model Option 1:
public class SchoolInfo
{
[Key, ForeignKey("School")]
public int schoolId { get; set; }
public virtual School School { get; set; }
}
SchoolInfo Model Option 2:
public class SchoolInfo
{
[ForeignKey("School")]
public int SchoolInfoId { get; set; }
public virtual School School { get; set; }
}
SchoolInfo Model Option 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);
An alternative way because of the restrictions you mentioned is something like:
Your actual Data Base:
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
)
School Model:
public class School
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int schoolId { get; set; }
public virtual SchoolInfo SchoolInfo { get; set; }
}
SchoolInfo Model Option 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 (I did not test it):
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);
You can see:
http://www.entityframeworktutorial.net/entity-relationships.aspx http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx
来源:https://stackoverflow.com/questions/37349886/ef-is-mapping-to-the-wrong-keys-on-entities