Search code examples
c#.netentity-frameworkef-code-firstentity-framework-4.1

Naming columns in self referencing virtual properties


I'm trying to name the parent and child columns to something more meaningful instead of Element_ID and Element_ID1.

The Element table is generated without issue, but the second table is what I'd like to update the column names on.

I've tried adding the attribute [Column("ParentID")] above the parent property deceleration, but it has no affect on the generated table.

Entity Class

public class Element
{
    public Guid ID { get; set; } 
    public string Title { get; set; }
    public int Status { get; set; }       

    public virtual List<Element> Parent { get; set; }
    public virtual List<Element> Child { get; set; }
}

Generated Migration

CreateTable(
    "dbo.ElementElements",
    c => new
        {
            Element_ID = c.Guid(nullable: false),
            Element_ID1 = c.Guid(nullable: false),
        })
    .PrimaryKey(t => new { t.Element_ID, t.Element_ID1 })
    .ForeignKey("dbo.Elements", t => t.Element_ID)
    .ForeignKey("dbo.Elements", t => t.Element_ID1)
    .Index(t => t.Element_ID)
    .Index(t => t.Element_ID1);

I can make the second table output as I want if I use a second entity as such

public class Hierarchy
{
    public Guid ID { get; set; } 
    public virtual Guid ParentID { get; set; }
    public virtual Element Parent { get; set; }
    public virtual Guid ChildID { get; set; }
    public virtual Element Child { get; set; }
}

Which generated the following create script

CreateTable(
    "dbo.Hierarchies",
    c => new
        {
            ID = c.Guid(nullable: false),
            ParentID = c.Guid(nullable: false),
            ChildID = c.Guid(nullable: false),
        })
    .PrimaryKey(t => t.ID)
    .ForeignKey("dbo.Elements", t => t.ParentID)
    .ForeignKey("dbo.Elements", t => t.ChildID)
    .Index(t => t.ParentID)
    .Index(t => t.ChildID);

So is it possible to achieve the generating the second table using the column names I want with just one entity class?


Solution

  • If I understand your question correctly you just need an ordinary many-to-many mapping with Fluent API:

    modelBuilder.Entity<Element>()
        .HasMany(e => e.Parent)
        .WithMany(e => e.Child)
        .Map(m => {
            m.ToTable("ElementMap"); // name of the link table
            m.MapLeftKey("ParentID");
            m.MapRightKey("ChildID");
        });
    

    I would expect that the generated migration will respect this mapping and use the supplied table and column names.