如何告诉该死的 Entity Framework 将关系映射到我们想要的列!
我有一张 table :
public class ShedPart
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int GroupId { get; set; }
public int ParentGroupId { get; set; }
public string GroupName { get; set; }
[ForeignKey("GroupId")]
[InverseProperty("ParentGroupId")]
public ICollection<Part> ParentParts { get; set; }
}
每个部分可以有多个父部分...
生成的 SQL 是这样的:
SELECT
`Project1`.`Id`,
`Project1`.`Name`,
`Project1`.`GroupId`,
`Project1`.`ParentGroupId`,
`Project1`.`GroupName`,
`Project1`.`C1`,
`Project1`.`Id1`,
`Project1`.`Name1`,
`Project1`.`GroupId1`,
`Project1`.`ParentGroupId1`,
`Project1`.`GroupName1`
FROM (SELECT
`Extent1`.`Id`,
`Extent1`.`Name`,
`Extent1`.`GroupId`,
`Extent1`.`ParentGroupId`,
`Extent1`.`GroupName`,
`Extent2`.`Id` AS `Id1`,
`Extent2`.`Name` AS `Name1`,
`Extent2`.`GroupId` AS `GroupId1`,
`Extent2`.`ParentGroupId` AS `ParentGroupId1`,
`Extent2`.`GroupName` AS `GroupName1`
CASE WHEN (`Extent2`.`Id` IS NULL) THEN (NULL) ELSE (1) END AS `C1`
FROM `Parts` AS `Extent1` LEFT OUTER JOIN `Parts` AS `Extent2` ON `Extent1`.`Id` = `Extent2`.`GroupId`) AS `Project1`
ORDER BY
`Id` ASC,
`C1` ASC}
如您所见,这是错误的,因为它是在 Id => GroupId 上加入表,而我试图通过 ParentGroupId => GroupId 加入。
所以我试试这个:
modelBuilder.Entity<Part>()
.HasMany(s => s.ParentParts)
.WithMany()
.Map(m =>
{
m.ToTable("parts");
m.MapLeftKey("GroupId");
m.MapRightKey("ParentGroupId");
});
做同样的事情......似乎 Entity Framework 只会映射到关键列!如何让它关联我想要的列?
最佳答案
你试过提取
[Key]
public int GroupId { get; set; }
public int ParentGroupId { get; set; }
到具有自连接的组表? 这样你就可以拥有 Part -> Group 的导航属性。
group 将包含零件的集合及其父组。
GroupId 将成为主键,您可以自行引用 ParentGroupId
关于c# - Entity Framework 4.1 通过设置外键映射关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5872507/