Inserting into Lookup Table

做~自己de王妃 提交于 2019-12-24 13:08:56

问题


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.



来源:https://stackoverflow.com/questions/20846111/inserting-into-lookup-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!