Entity structure - many to many

Hi, I am trying to use many-many relationships with the EF Fluent API. I have 2 POCO classes.

public class Project { public int ProjectId { get; set; } public virtual ICollection<Author> Authors { get; set; } public Project() { Authors = new List<Author>(); } } public class Author { public int AuthorId { get; set; } public virtual ICollection<Project> Projects { get; set; } public Author() { Projects = new List<Project>(); } } 

And I map many, many relationships to this part of the code:

  ////MANY TO MANY modelBuilder.Entity<Project>() .HasMany<Author>(a => a.Authors) .WithMany(p => p.Projects) .Map(m => { m.ToTable("ProjectAuthors"); m.MapLeftKey("ProjectId"); m.MapRightKey("AuthorId"); }); 

This created ProjectsAuthors table in the database. This is my first attempt at matching this relationship.

If I skipped this mapping, he created an AuthorProject table with a similar schema. Is this bevahior right?

+3
source share
1 answer

As a result of trial and error, I found the following. Given two classes ...

 public class AClass { public int Id { get; set; } public ICollection<BClass> BClasses { get; set; } } public class BClass { public int Id { get; set; } public ICollection<AClass> AClasses { get; set; } } 

... and there is no Fluent mapping and DbContext like this ...

 public class MyContext : DbContext { public DbSet<AClass> AClasses { get; set; } public DbSet<BClass> BClasses { get; set; } } 

... name of the created BClasslasses connection table . If I change the order of the sets ...

 public class MyContext : DbContext { public DbSet<BClass> BClasses { get; set; } public DbSet<AClass> AClasses { get; set; } } 

... the name of the created join table changes to AClassBClasses , and the order of the key columns in the table also changes. Thus, the name of the join table and the order of the key columns, apparently, depend on the order in which the object classes are β€œloaded” into the model, which may be the order of the DbSet or another order, if there is more relation - for example, some other object referring to AClass .

In the end, it makes no difference, because such a many-to-many relationship is "symmetrical." If you want to have your own connection table name, you can specify it in the Fluent API, as you already did.

So, to your question: Yes, naming the AuthorProjects connection table AuthorProjects is the correct behavior. If the name was ProjectAuthors , that would be the correct behavior, though.

+6
source

Source: https://habr.com/ru/post/900512/


All Articles