插入查询表 [英] Inserting into Lookup Table

查看:79
本文介绍了插入查询表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是实体框架的新手,我尝试使用一些数据,下面有3个表:
问题是我发现,许多关系aux表没有抽象到实体框架中。

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.

问题:

我目前有可以创建好友的用户。如果他们创建了一个朋友实体框架,那么框架应该会在Users_Friends中创建必要的条目。

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

但是!如果我让用户填写一个表单来创建一个朋友,而他们创建的朋友已经存在于朋友中,那该怎么办,所以我们只想在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. 如果朋友电话号码已存在,则它们是重复的。 (无需插入此朋友)

  3. 获取此匹配的朋友ID

  4. 将当前用户ID插入Users_Friends并插入匹配的朋友ID 。

  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.

但是实体不允许我访问Users_Friends表。

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;
}

我不知道如何将FriendId和UserId插入Users_Friends。 / p>

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

推荐答案

您可以执行以下操作:

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

Friend 实例添加到 User.Friends ,告诉EF保存时在连接表中插入一条记录。

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

这篇关于插入查询表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆