EF4 CTP5 self-referencing hierarchical entity mapping

廉价感情. 提交于 2019-12-12 08:16:27

问题


Okay, this should be really easy, but I've been tearing my hair out. Here's my POCO (which has to do with machine parts, so a part can be contained within a parent part):

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

When the database table is created, the column names are "ID", "Name", and "PartID". How do I change the name of that last column to "ParentPartID"?


回答1:


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


来源:https://stackoverflow.com/questions/4612053/ef4-ctp5-self-referencing-hierarchical-entity-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!