简体   繁体   English

使用实体框架将对象添加到包含其他对象列表的表中

[英]Add object to table containing List of other objects using Entity Framework

I'm adding an object to a table in the database, adding a contact of MarketingContact type. 我正在向数据库中的表添加对象,添加了MarketingContact类型的contact These are my model classes: 这些是我的模型类:

public class MarketingContact
    {
        public MarketingContact()
        {
            this.ContactTags = new List<ContactTag>();
        }

        public int id { get; set; }
       //..some other properties not complex properties...
        public virtual ICollection<ContactTag> ContactTags { get; set; }
    }

This is the ContactTag model: 这是ContactTag模型:

 public class ContactTag
    {
        public ContactTag()
        {
            this.MarketingContacts = new List<MarketingContact>();
        }

        public int TagId { get; set; }
       //some other no complex properties...
        public virtual ICollection<MarketingContact> MarketingContacts { get; set; }
    }

And this is my AddContact() method in my controller: 这是我控制器中的AddContact()方法:

 [HttpPost]
        public ActionResult AddContact(MarketingVM marketingContactVM)
        {            
            List<ContactTag> contactTags = new List<ContactTag>();
            for (int i = 0; i < marketingContactVM.MarketingContacts.Count; i++)
            {
                if (marketingContactVM.MarketingContacts[i].IsSelected==true)
                {
                    contactTags.Add(new ContactTag { Name = marketingContactVM.MarketingContacts[i].Name, TagId = marketingContactVM.MarketingContacts[i].TagId,
                    InfusionSoftId = marketingContactVM.MarketingContacts[i].InfusionSoftId});
                }
            }
            MarketingContact marketingContact = AutoMapper.Mapper.Map<MarketingContact>(marketingContactVM);
            marketingContact.ContactTags = contactTags;                  
             context.MarketingContacts.Add(marketingContact);
             context.SaveChanges();          
            return Json(new { result = "success"}, JsonRequestBehavior.AllowGet);
        }    

Note that in my controller action I'm making use of a ViewModel( MarketingVM type ). 请注意,在我的控制器操作中,我使用了ViewModel( MarketingVM type )。 At the time that I save into the database the MarketingContact object is saved in the MarketingContacts table, but in the ContactTags table new rows are created depending on what the ContactTags ICollection that belong to marketingContact contains, and I'm just selecting from ContactTags , the rows are already there, I don't need more rows with same values added in ContactTags table, why is this happening? 在将我保存到数据库时, MarketingContact对象保存在MarketingContacts表中,但是在ContactTags表中,根据属于marketingContactContactTags ICollection包含的内容创建新行,而我只是从ContactTags选择行已经在那里,我不需要在ContactTags表中添加具有相同值的更多行,为什么会发生这种情况? At the moment I save the object into the database the marketingContact object contains a ContactTags collection with fields existing in the ContactTags table, including the correct TagId values, but instead of just relate them to that row in the MarketingContacs table it create new rows in the ContactTags table with the same values except for the TagId (it generates a new value) therefore the values are duplicated everytime in the ContactTags table and I don't need that. 目前,我将对象保存到数据库中时, marketingContact对象包含一个ContactTags集合,其中具有ContactTags表中现有的字段,包括正确的TagId值,但它不只是将它们与MarketingContacs表中的该行相关,而是在除了TagId之外, ContactTags表具有相同的值(它会生成一个新值),因此,每次在ContactTags表中都重复这些值,而我则不需要。 What would I need to change? 我需要改变什么?

The problem is that when you call 问题是当您打电话时

context.MarketingContacts.Add(marketingContact);

EF iterates the ContactTags collection and marks each object which is not currently tracked by (loaded in, attached to) context as new. EF迭代ContactTags集合,并将当前未被(加载,附加到)上下文跟踪的每个对象标记为新对象。

Since you know they are existing entities, you have to tell that to EF. 由于您知道它们是现有实体,因此您必须将其告知EF。 One way to do that is to attach them to the context (which will mark them as Unchanged ) before adding the main entity. 一种方法是在添加主实体之前将它们附加到上下文(将它们标记为Unchanged )。

For instance, you can change 例如,您可以更改

contactTags.Add(new ContactTag { Name = marketingContactVM.MarketingContacts[i].Name, TagId = marketingContactVM.MarketingContacts[i].TagId,
InfusionSoftId = marketingContactVM.MarketingContacts[i].InfusionSoftId});

to

// Note: setting just TagId would be enough
var contactTag = new ContactTag { Name = marketingContactVM.MarketingContacts[i].Name, TagId = marketingContactVM.MarketingContacts[i].TagId,
InfusionSoftId = marketingContactVM.MarketingContacts[i].InfusionSoftId};
contactTags.Add(contactTag);
// the next line will give you the desired behavior
context.ContactTags.Attach(contactTag);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Entity Framework中更新包含对象列表的对象的最佳方法 - Best way to update an object containing a list of objects in Entity Framework 包含实体框架中其他模型列表的模型 - Model containing a list of other model in Entity Framework 如何使用Entity Framework将多个对象添加到外表 - How to add multiple objects to a foreign table using Entity Framework 使用实体框架将列表对象分为两个对象 - Divide List object in two objects with Entity Framework 使用Dynamic Linq Core和Entity Framework 2.0创建包含列表的对象 - Create object containing a list using Dynamic Linq Core with Entity Framework 2.0 使用jQuery Ajax,如何发布一个包含其他对象列表的对象 - Using jquery ajax, how do you post an object containing a list other objects 使用Reflection动态地向Entity Framework添加对象 - Add object to Entity Framework dynamically using Reflection 使用实体框架添加/更新实体列表 - Add/Update a list of entities using the entity framework 使用实体框架将表连接到列表 - Joining table to a list using Entity Framework 使用实体框架选择子对象列表时如何获得对相关父对象的引用 - How do get reference to a related parent object when selecting a list of child objects using entity framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM