首页 > 解决方案 > 更新类 c# 的属性

问题描述

我的项目中有以下 POCO:

 public class FileTranslationData
{
    public string Id { get; set; }
    public string FileLocation { get; set; }
    public string FileJSONLocation { get; set; }
    public int TranslationRetries { get; set; }
    public string TranslationStatus { get; set; }
    public string TranslationId { get; set; }
    public string FileTranslationURL { get; set; }
    public string TranslatedFileURL { get; set; }
    public string ProcessStatus { get; set; }
    public int FileDownLoadRetries { get; set; }
    public int FileUploadRetries { get; set; }
    public int RetryDuration { get; set; }
    public string Errors { get; set; }
    public DateTime LastRetryTime { get; set; }
    public string StatusLog { get; set; }
}

我用它来将数据保存到 LiteDB 和从 LiteDB 保存数据,以帮助在我的过程中保持文件进展状态。如果我需要更新这个类的某些属性,我从数据库中检索它,进行更改然后重新保存到数据库,没问题。我使用这个类来检测对象的变化(从另一个答案中提取和修改):

 public static List<string> GetChangeProperties<T>(T a, T b) where T:class 
    {
       if(a != null && b != null)
        {
            if(object.Equals(a,b))
            {
                return new List<string>();
            }
            var allProperties = a.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            return allProperties.Where(p => !object.Equals(p.GetValue(a), p.GetValue(b))).Select(p => p.Name).ToList();
        }
        else
        {
            var aText = $"{(a == null ? ("\"" + nameof(a) + "\"" + " was null") : "")}";
            var bText = $"{(b == null ? ("\"" + nameof(b) + "\"" + " was null") : "")}";
            var bothNull = !string.IsNullOrEmpty(aText) && !string.IsNullOrEmpty(bText);
            throw new ArgumentNullException(aText + (bothNull ? ", " : "") + bText);
        }
    }

这将返回对象之间已更改的属性列表。获得更改的属性列表后,我只想更新第一个对象中基于第二个对象更改的属性,然后再将更新重新保存回数据库。我正在寻找一种更好的更改属性的方法的帮助,而不是使用 switch 语句并检查所有属性(如果它们不同并且只更改已更改的属性)。

谢谢。

标签: c#

解决方案


推荐阅读