简体   繁体   English

如何将实体添加到现有实体MVC 2 EF

[英]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.

相关问题 MVC / EF-如何添加实体关联 - MVC/EF - How to add an entity association 在EF(实体框架)中将城市添加到现有国家/地区 - Add A City To An Existing Country In EF(Entity Framework) 将实体添加到现有实体位置C#EF - Add an entity into existing entity position C# EF 如何使用实体框架将现有实体添加为新实体 - How to Add existing entity as a new Entity with Entity Framework 如何将新对象添加到现有实体,将数据放入数据中并让EF将其添加到数据库中? - How can I add a new object to an existing Entity, PUT the data and have EF add it to my database? EF 4插入实体与现有实体的关系 - EF 4 insert entity in relationship with existing entity 无法在EF4中将父实体与现有子实体一起添加 - Unable to add parent entity with existing child entities in EF4 EF Core 更新现有实体 - EF Core update an existing entity 如何在不重复的情况下添加与现有实体关系的新实体? (EF 6.1) - How to add a new entity with relationships to existing entities without getting duplicates? (EF 6.1) EF Core 多对多插入:如何很好地避免 EF 尝试添加已经存在的唯一约束子实体? - EF Core many-to-many insert : how to nicely avoid EF trying to add an already existing unique-constraint sub-entity?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM