[英]How to add an entity to an existing entity MVC 2 EF
I am creating a MVC 2 website. 我正在创建一个MVC 2网站。 I'm a beginner. 我是初学者。 I created a Model to use EF. 我创建了一个使用EF的模型。 The relationship is between a user table and a product table (one to many relationship). 该关系在用户表和产品表之间(一对多关系)。 I am able to create new users and save them on the DB using linq to entities. 我能够创建新用户并将其使用linq实体保存到数据库中。 My question is how do I add a product to an existing user. 我的问题是如何向现有用户添加产品。 I was starting with the code below but it does not work. 我从下面的代码开始,但是没有用。 Intellisense doesn't see the queryuser.Product whats wrong with my code or what is the right way to do it. Intellisense看不到queryuser.Product我的代码有什么问题或正确的方法是什么。 If someone can help me it would be great 如果有人可以帮助我,那就太好了
public void Insert(Product obj)
{
if (HttpContext.Current.Session["userid"] != null)
{
string userid2 = HttpContext.Current.Session["userid"].ToString();
var queryuser = from p in entities.Users
where p.UserID == userid2
select p;
queryuser.Product.Add(obj);
entities.Users.Add(queryuser);
entities.SaveChanges();
}
}
I am calling this method from my controller. 我正在从控制器中调用此方法。
queryuser
is an IQueryable and you are treating it like a single object. queryuser
是一个IQueryable,您将其queryuser
单个对象。
You might try replacing: 您可以尝试更换:
queryuser.Product.Add(obj);
entities.Users.Add(queryuser);
with 同
user = queryuser.First();
user.Product.Add(obj);
entities.Users.Add(user);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.