Entity Framework 验证外部实体未被修改

Entity Framework validate external entity is not modified

我正在尝试验证来自外部上下文的实体是否未更改。

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;
    }
} 

我想附加并验证附加的实体没有根据数据库中的内容进行修改。

我宁愿不必手动迭代属性。有没有办法解决这个问题?

你可以试试:

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

适合我!

无需附加外部实体。您可以使用外部实体来设置数据库实体的值,然后检查后者的状态:

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.
}