开发者

EF4 CTP5 self-referencing hierarchical entity mapping

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 data开发者_JAVA百科base table is created, the column names are "ID", "Name", and "PartID". How do I change the name of that last column to "ParentPartID"?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜