EF CF: Many-to-Many Relationship with More Information

We have an outdated database, and we map new objects and details to old tables and columns. So far, so good. We have a many-to-many relationship that has been matched successfully. The intermediate table contains additional data. When we try to map an intermediate table to an object, we get an exception that the mapping is already defined. If we remove the display from either side of the relationship, we get an error that is not in the table (ofc, we expect just that). I can do this easily with NHibernate, and I'm starting to think that EF is really missing really a lot of features. So please tell me that I'm wrong, and we can do it with EF.

Best wishes

EDIT: Here is a dummy pattern that fails.

class User { public ICollection<User> Followers{get;set;} } class UserRelation { public User User{get;set;} public User Follower{get;set;} public DateTime CreatedOn{get;set;} } 

user mapping

 modelBuilder .Entity<User>() .HasMany<User>(user => user.Followers) .WithMany() .Map(m =>m.MapLeftKey("user_id").MapRightKey("follower_id") .ToTable("user_follower")); 

user relationship mapping

 modelBuilder .Entity<UserRelation>() .ToTable("user_follower"); modelBuilder .Entity<UserRelation>() .HasOptional<User>(f => f.User) .WithRequired().Map(m => m.MapKey("user_id")); modelBuilder .Entity<UserRelation>() .HasOptional<User>(f => f.Follower) .WithRequired().Map(m => m.MapKey("follower_id")); modelBuilder .Entity<UserRelation>() .Property(entity => entity.CreatedOn) .HasColumnName("created_on"); 

Exception

The specified schema is invalid. Errors: (67.6): error 0019: EntitySet 'UserUser' with schema 'dbo' and table 'user_follower' already defined. Each EntitySet must reference a unique schema and table.

Edit2: Here is another example of this model: http://learnentityframework.com/LearnEntityFramework/tutorials/many-to-many-relationships-in-the-entity-data-model/

+3
source share
2 answers

Direct many-to-many mapping is only available if the connection table contains only foreign keys. If you want to expand other properties in the connection table, you must map it to a single object and display two one-to-many relationships from the old objects used in many-to-many.

I really cannot write you code because I do not understand your example.

Try it only (do not call the "Many to many in the user"):

 modelBuilder.Entity<UserRelation> .HasRequired(r => r.User) .WithMany(u => u.Followers); modelBuilder.Entity<UserRelation> .HasRequired(r => r.Follower) .WithMany(); 
+9
source

EF displays many-to-many relationships as properties of related objects.

So, let's say you have Cars and Drivers that are associated with m-to-n. In your EF model, you will see that each Car object has a Drivers collection as a property, and each Driver object has a Cars collection as a property.

This is how m-to-n relationships are modeled in EF.

+1
source

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


All Articles