且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在实体框架中保存相关实体的通用方法

更新时间:2023-12-01 15:38:46

您的问题是知道要附加的正确Collection,我想如果您创建了一个参数,则可以使其生效. /blockquote>

Does anyone have any ideas how to make a generic methd to save collections in entity framework. In my webapp i have tons of pages where user edits variable length collections and i end up writing the following code over and over again. Is there any way i can turn it into a generic method, so that those entities that are not in the database are added, those that exist are updated, rest are deleted.


private void SavePhoneNumbers(User user, IList<PhoneNumber> phoneNumbers)
{
    // Get ids of entities that allready exist in db(entities where id is greater than zero).New entities have zero for id.
    var idsOfNumsToKeep = phoneNumbers.Where(p => p.Id > 0).Select(p => p.Id).ToArray();
    
    //Delete entities from db that are not in 'idsOfNumsToKeep'-array, because user
    //has deleted them
    var numsToDelete = context.PhoneNumber.Where(p => p.UserId == user.Id && !idsOfNumsToKeep.Contains(p.Id));

    foreach(var num in numsToDelete)
        context.PhoneNumber.DeleteObject(num);

    foreach (var num in phoneNumbers)
    {
        num.UserId = User.Id;
        // An exsiting number update it
        if(num.Id > 0)
        {
            context.PhoneNumber.Attach(num)
            context.ObjectStateManager.ChangeObjectState(num, EntityState.Modified);
        }
        else{
            // It's a new number add it
            context.PhoneNumber.AddObject(num);
        }
    }
}

Your issue is knowing the correct Collection to attach to, I imagine if you made that a parameter, then you could make it work.