EF4 CTP5 self-referencing hierarchical entity mapping

扶醉桌前 提交于 2019-12-03 17:08:21

Basically, you want to rename the foreign key in an Independent Association and this is the fluent API code that will do it:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Part>()
                .HasOptional(p => p.ParentPart)
                .WithMany()
                .IsIndependent()
                .Map(m => m.MapKey(p => p.ID, "ParentPartID"));
}

However, due to a bug in CTP5, this code throw as exception in self referencing associations (which is your association type). The workaround would be to change your association to a Foreign Key Association as follows:

public class Part
{
    public int ID { get; set; }
    public string Name { get; set; }                
    public int ParentPartID { get; set; }

    [ForeignKey("ParentPartID")]
    public Part ParentPart { get; set; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!