仅更新不同的更改 [英] Update only the changes that are different

查看:133
本文介绍了仅更新不同的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体集 employee_table ,我正在通过excel表获取数据,我已经在内存中加载,用户将点击保存以保存数据库中的更改,并且首次插入记录,并且没有问题。

I have a Entity-Set employee_table, I'm getting the data through excel sheet which I have loaded in the memory and the user will click Save to save the changes in the db and its all good for the first time inserting records and no issue with that.

但是如何我只更新所做的更改?这意味着,假设我有10行和5列,10行表示第7行被修改,5列中的第3列被修改,我只需要更新这些更改并保持其他的现有值列。

but how can I update only the changes that are made? meaning that, let say I have 10 rows and 5 columns and out of 10 rows say row 7th was modified and out of 5 column let say 3rd column was modified and I just need to update only those changes and keep the existing value of the other columns.

我可以检查 if(myexistingItem.Name!= dbItem.Name){// update} 但是它非常繁琐而且效率不高,我相信有更好的处理方式。

I can do with checking if (myexistingItem.Name != dbItem.Name) { //update } but its very tedious and not efficient and I'm sure there is a better way to handle.

这里是我到目前为止。

var excelData = SessionWrapper.GetSession_Model().DataModel.OrderBy(x => x.LocalName).ToList();;
var dbData = context.employee_master.OrderBy(x => x.localname).ToList();

employee_master = dbEntity = employee_master();

if (dbData.Count > 0)
{
   //update
   foreach (var dbItem in dbData)
   {
      foreach(var xlData in excelData)
      {
         if(dbItem.customer == xlData.Customer)
         {
            dbEntity.customer = xlData.Customer;
         }
         //...do check rest of the props....
         db.Entry(dbEntity).State = EntityState.Modified;
         db.employee_master.Add(dbEntity);
      }
   }

   //save
   db.SaveChanges();
}
else
{
  //insert
}


推荐答案

您可以通过反思使此检查更通用。

You can make this checking more generic with reflection.

使用此答案按属性名称值。

public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

使用此答案通过属性名称设置值

public static void SetPropertyValue(object obj, string propName, object value)
{
    obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}

这个答案是列出所有属性

public static void CopyIfDifferent(Object target, Object source)
{
    foreach (var prop in target.GetType().GetProperties())
    {
        var targetValue = GetPropValue(target, prop.Name);
        var sourceValue = GetPropValue(source, prop.Name);
        if (!targetValue.Equals(sourceValue))
        {
            SetPropertyValue(target, prop.Name, sourceValue);
        }
    }
}

strong>:如果您需要排除某些属性,可以通过将属性列表传递给该方法来实现非常简单,如果被排除或不排除,则可以在中查看。

Note: If you need to exclude some properties, you can implement very easy by passsing the list of properties to the method and you can check in if to be excluded or not.

这篇关于仅更新不同的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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