Reputation: 1785
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?
Upvotes: 1
Views: 164
Reputation: 11
For EF 6, I used the answer posted by Slauma on the current thread https://stackoverflow.com/a/15147308/13808871, but the column names on the relationship table were switched, to fix it, I exchanged the names of the parameters on the MapLeftKey and MapRightKey configuration methods.
modelBuilder.Entity<Element>()
.HasMany(e => e.Parent)
.WithMany(e => e.Child)
.Map(m =>
{
m.ToTable("ElementMap");
m.MapLeftKey("ChildID");
m.MapRightKey("ParentID");
});
Hope this helps!
For more information go to the Microsoft documentation
Upvotes: 0
Reputation: 177133
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.
Upvotes: 2