在实体框架中保存相关实体的通用方法 [英] Generic method to save related entities in entity framework

查看:76
本文介绍了在实体框架中保存相关实体的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有人对如何制作通用方法以将集合保存在实体框架中有任何想法.在我的Web应用程序中,我有成千上万的页面,用户可以在其中编辑可变长度的集合,最终我会一遍又一遍地编写以下代码.有什么办法可以将其转换为通用方法,以便添加不在数据库中的那些实体,更新那些存在的实体,删除其余的实体.


 私有  void  SavePhoneNumbers(用户,IList< PhoneNumber>电话号码)
{
    // 获取db中已经存在的实体的id(id大于零的实体). ID.
     var  idsOfNumsToKeep = phoneNumbers.Where(p = >  p.Id  0 ).选择(p = // 由于用户,从数据库中删除不在"idsOfNumsToKeep"数组中的实体
    // 已将其删除
     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 电话号码中)
    {
        num.UserId = User.Id;
        // 一个现有号码对其进行了更新
        如果(数字ID >   0  )
        {
            context.PhoneNumber.Attach(num)
            context.ObjectStateManager.ChangeObjectState(num,EntityState.Modified);
        }
        其他 {
            // 这是一个新数字
            context.PhoneNumber.AddObject(num);
        }
    }
} 

解决方案

您的问题是知道要附加的正确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.


这篇关于在实体框架中保存相关实体的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆