我正在嘗試驗證來自外部背景關系的物體沒有改變。
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
我有一個方法,它接收一個尚未從背景關系加載的物體。
public bool Validate(Employee employee)
{
using (var context = new Context())
{
return context.Entry(employee).State == EntityState.Modified;
}
}
我想附加并驗證附加的物體沒有從資料庫中的內容中修改。
我不想手動迭代屬性。有沒有辦法解決這個問題?
uj5u.com熱心網友回復:
無需附加外部物體。您可以使用外部物體設定資料庫物體的值,然后檢查后者的狀態:
public bool Validate(Employee externalEmployee)
{
using var context = new Context(); // C# 8.0
var dbEntity = context.Where(x => x.Id == externalEmployee.Id).SingleOrDefault();
if (dbEntity != null)
{
context.Entry(dbEntity).CurrentValues.SetValues(externalEmployee);
return context.Entry(dbEntity).State == EntityState.Modified;
}
return false; // Or true, depending on your semantics.
}
uj5u.com熱心網友回復:
你可以試試:
public static List<string> GetChanges<T>(this T obj, T dbObj)
{
List<string> result = new List<string>();
var type = typeof(T);
foreach (var prop in type.GetProperties())
{
var newValue = prop.GetValue(obj, null);
var dbValue = prop.GetValue(dbObj, null);
if(newValue == null && dbValue != null)
{
result.Add(prop.Name);
continue;
}
if (newValue != null && dbValue == null)
{
result.Add(prop.Name);
continue;
}
if (newValue == null && dbValue == null)
continue;
if (!newValue.ToString().Equals(dbValue.ToString()))
result.Add(prop.Name);
}
return result;
}
如果 resultList.Count > 0,則您的物件發生了變化。
在您的驗證方法中:
public bool Validate(Employee employee)
{
using (var context = new Context())
{
Employee dbEmployee = context.Employee.Find(employee.Id);
if(employee.GetChanges(dbEmployee).Count > 0)
return true;
return false;
}
}
這是一個上帝的解決方法=D
對我有用!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/387444.html
上一篇:Laravel8驗證required_without
下一篇:如何對只讀實體屬性執行輸入驗證?
