Inserting into Lookup Table

2019-08-04 08:23发布

问题:

I am new to entity framework and I am trying to work with some data I have the 3 tables below: Problem is I have found out that many to many relationships aux tables are not abstracted into entity framework.

Problem:

I currently have users who can create Friends. If they create a friend entity frameworks will supposedly create the necessary entries into Users_Friends.

But! What if I have the user fill out a form to create a friend and the friend they created already exists in friends, so instead of duplicating the friend we simply just want to make an insert into Users_Friends.

In my mind I am stepping through this way:

  1. Grab Post Data
  2. If Friend PhoneNumber already exists they are duplicate. (no need to insert this friend)
  3. Grab this matched Friends Id
  4. Insert our current users id into Users_Friends as well as insert the matched Friend Id.

But entity doesn't give me access to the Users_Friends table.

I did find out through another post though that I can select all the friends associated with a friend by doing:

using (var db = new GameAlertDBEntities())
{
    var user = db.Users.First(); // or any other query for user
    var friends = user.Friends;
}

I cant figure out though how to insert just FriendId and UserId into Users_Friends.

回答1:

You can do this:

var user = db.Users.Find(userID);
var friend = db.Friends.Find(friendID);
user.Friends.Add(friend);
db.SaveChanges();

When you add the Friend instance to User.Friends, that tells EF to insert a record in the join table when you save.