1

Using code-first with Entity Framework 6.

I've this entity:

public class LineSection
{
    public int Id { get; set; }
    public List<LineSection> Next { get; set; }
    public List<LineSection> Previous { get; set; }
}

I add a migration, just to see how the database will be:

        CreateTable(
            "dbo.LineSectionLineSections",
            c => new
                {
                    LineSection_Id = c.Int(nullable: false),
                    LineSection_Id1 = c.Int(nullable: false),
                })
            .PrimaryKey(t => new { t.LineSection_Id, t.LineSection_Id1 })
            .ForeignKey("dbo.LineSections", t => t.LineSection_Id)
            .ForeignKey("dbo.LineSections", t => t.LineSection_Id1)
            .Index(t => t.LineSection_Id)
            .Index(t => t.LineSection_Id1);

I don't like the default naming. Can I change the tablename (LineSectionLineSections) and the two foreignkeys (LineSection_Id and LineSection_Id1). Using modelbuilder, data attributes or some other way?

Karsten
  • 8,015
  • 8
  • 48
  • 83
  • `MapLeftKey`, `MapRightKey`. There are many examples, for instance https://stackoverflow.com/questions/16490334/how-to-define-many-to-many-relationship-through-fluent-api-entity-framework – Ivan Stoev Dec 06 '18 at 13:02
  • Please show a complete example for my case. As far as I can see, your examples doesn't fit my case as there is only list in the entity and not two. – Karsten Dec 06 '18 at 13:17
  • It doesn't really matter, but there you go. – Ivan Stoev Dec 06 '18 at 13:35

1 Answers1

2

The configuration on many-to-many relationship with implicit join table (doesn't matter if t is self or not) is performed with Map fluent API. You can use ToTable to specify the table name and MapLeftKey / MapRightKey to specify the corresponding column names (left is the entity being configured, right is the other end of the relationship).

So in your case it would be something like this:

modelBuilder.Entity<LineSection>()
   .HasMany(e => e.Next)
   .WithMany(e => e.Previous)
   .Map(m => m.MapLeftKey("PrevId")
          .MapRightKey("NextId")
          .ToTable("LineSectionLinks")
   );
Karsten
  • 8,015
  • 8
  • 48
  • 83
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343