具有2个外键实体表的表 [英] Table with 2 foreign keys entity framework

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

问题描述

我有一个包含2个外键的表。这些只是表中的元素。该表旨在在其他2个表之间创建关联。例如:该表是Users_Products,仅有的两列是UserId和ProductID,均为外键。当我从数据库生成EF对象时,它没有创建Users_Products对象,而只是自动创建了导航属性。现在如何使用EF在我的Users_Products表中插入数据?

I have a table which consists of 2 foreign keys. And those are only elements of the table. The table is meant to create association between 2 other tables. For example: The table is Users_Products, and the only 2 columns are UserId and ProductID, both foreign keys. When I generated the EF object from database it didn't create Users_Products object, it only automatically created navigation properties. Now how can I insert data in my Users_Products table using EF?

推荐答案

您可以获取一些用户对象并将产品添加到其导航中

You can get some user object and add product into its navigation property.

User user = context.Users.Where(u => u.Id == 1);
Product product = context.Products.Where(p => p.Id == 1);
user.Products.Add(product);
context.SaveChanges();

这篇关于具有2个外键实体表的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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