c# - 更新类 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 语句并检查所有属性(如果它们不同并且只更改已更改的属性)。
谢谢。
解决方案
推荐阅读
- tensorflow - keras stack LSTM:当输入在时间步长上移动时,为什么中间层输出没有移动?
- javascript - 功能 this.click 不适用于 casperjs
- javascript - Javascript:如何为对象数组中的对象属性设置值?
- php - MySQL 升级导致简单 WHERE 子句出现意外结果
- javascript - 替换Node JS中的文件路径
- python-3.x - 减少对'_thread.lock'对象的{方法'acquire'}python的调用次数
- firebase - 从 firebase 获取数据后视图中的 SwiftUI 图像未更新
- python - 如何在 lua 中创建 Python 生成器?
- reactjs - 进行菜单选择时如何关闭 react/material-ui 菜单/子菜单层次结构
- azure - 使用 Bicep 将 API 管理私有 IP 地址输入私有 DNS 条目时,不需要模板函数“引用”