EF4 CTP5 self-referencing hierarchical entity mapping
Asked Answered
S

1

3

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"?

Steeplejack answered 6/1, 2011 at 5:32 Comment(0)
U
2

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; }
}
Upgrowth answered 16/1, 2011 at 18:34 Comment(1)
.. and due to another bug in CTP5, this attribute will be ignored, along with the ParentPart property name ;-)Commodore

© 2022 - 2024 — McMap. All rights reserved.