【问题标题】:Entity Framework validate external entity is not modified实体框架验证外部实体未修改
【发布时间】:2022-01-18 22:13:58
【问题描述】:
我正在尝试验证来自外部上下文的实体没有改变。
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;
}
}
我想附加并验证附加的实体没有从数据库中的内容修改。
我不希望手动迭代属性。有没有办法解决这个问题?
【问题讨论】:
标签:
c#
entity-framework
validation
【解决方案1】:
你可以试试:
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
为我工作!
【解决方案2】:
无需附加外部实体。您可以使用外部实体设置数据库实体的值,然后检查后者的状态:
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.
}