I have a generated table via fluent API as follows:
modelBuilder.Entity<Person>()
.HasMany(m => m.Friends)
.WithMany()
.Map(w => w.ToTable("Friendship").MapLeftKey("PersonID").MapRightKey("FriendID"));
And this works fine, the table is generated correctly. But in my Data Access Layer, how can I execute CRUD functions on this table 'Friendship' via Entity Framework? Because I can't do something like this:
db.Friendships.Add(entity);
because 'Friendship' isn't defined in my DBContext.
What is the best way to approach this problem? Manually create a model or hardcode SQL queries in the Data Access Layer? Or another solution?
You cannot directly access the Friendship entity because it doesn't exist. The way Entity Framework treats a many-to-many relationship, the Friendship table is invisible and never modeled. If you want it available as an entity, you have to explicitly add the entity to the model and replace your many-to-many relationship with two one-to-many relationships.
If all you're asking is how to create the relationships between entities in a many-to-many in entity framework, it should be as simple as adding the references to the collections.
If
Person1
andPerson2
are entities, thenPerson1.Friends.Add(Person2)
should do the trick.