对现有Entity Framework对象的PUT请求

时间:2013-07-12 19:11:03

标签: c# entity-framework entity

我有5个实体框架模型,它们都彼此有关系。向数据库发布一个新的很简单,但尝试通过PUT请求更新它们变得非常混乱。我必须手动进入每个集合并更新正在更改的内容。

        private void updateRelation(Dealer dealer)
    {
        var dealerOld = db.Dealers.Include(d => d.Contacts).Single(d => d.DealerID == dealer.DealerID);
        var contactsNew = dealer.Contacts;
        List<int> contactIds = new List<int>();

        if (dealer.DealerGroup == null ||
            dealerOld.DealerGroup == null ||
            dealer.DealerGroup.DealerGroupID != dealerOld.DealerGroup.DealerGroupID)
        {

            if (dealerOld.DealerGroup != null)
            {
                DealerGroup d = db.DealerGroups.Find(dealerOld.DealerGroupID);
                d.Dealers.Remove(dealerOld);
            }

        }

        updateManyToMany(dealer,dealerOld,contactIds,contactsNew);
    }

    private void updateManyToMany(Dealer dealer, Dealer dealerOld, List<int> contactIds, ICollection<Contact> contactsNew  )
    {

        foreach (var contact in contactsNew)
        {
            contactIds.Add(contact.ContactID);
        }

        foreach (var contact in dealerOld.Contacts.ToList())
        {
            if (!contactIds.Contains(contact.ContactID))
            {
                dealerOld.Contacts.Remove(contact);
            }
        }

        foreach (int contactId in contactIds)
        {
            if (!dealerOld.Contacts.Any(c => c.ContactID == contactId))
            {
                var contact = new Contact() { ContactID = contactId };
                dealerOld.Contacts.Add(contact);
                db.Contacts.Attach(contact);
            }
        }
    }

有一种更简单的方法吗

1 个答案:

答案 0 :(得分:0)

还有许多与此相关的问题,您可能需要花费一点时间来筛选解决方案,同时或者等待更有帮助的答案。