【发布时间】:2015-09-03 05:14:39
【问题描述】:
我正在研究一种使用反射比较两个对象的方法。对象类型是从实体框架创建的对象。当我使用 GetProperties() 时,我得到了 EntityCollection 和 EntityReference 属性。我只想要属于该对象的属性,而不想要任何关联的属性或来自外键的引用。
我尝试了以下How to get all names of properties in an Entity?。
我考虑过传递一组属性进行比较,但我不想为每个对象类型都输入它们。我愿意接受一些建议,即使是那些不使用反射的建议。
public bool CompareEntities<T>(T oldEntity, T newEntity)
{
bool same = true;
PropertyInfo[] properties = oldEntity.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
var oldValue = property.GetValue(oldEntity, null);
var newValue = property.GetValue(newEntity, null);
if (oldValue != null && newValue != null)
{
if (!oldValue.Equals(newValue))
{
same = false;
break;
}
}
else if ((oldValue == null && newValue != null) || (oldValue != null && newValue == null))
{
same = false;
break;
}
}
return same;
}
【问题讨论】:
-
这些实体是 POCO 还是派生自
EntityObject?