gpt4 book ai didi

c#-4.0 - 获取实体对象的属性名称,不包括entitycollection和entityreference

转载 作者:行者123 更新时间:2023-12-03 06:34:35 25 4
gpt4 key购买 nike

我正在研究一种使用反射比较两个对象的方法。对象类型是从 Entity Framework 创建的对象。当我使用 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;
}

最佳答案

使用@Eranga 和 https://stackoverflow.com/a/5381986/1129035 的建议我能够想出一个可行的解决方案。

由于根对象中的某些属性是 GenericType,因此需要两个不同的 if 语句。仅当当前属性是 EntityCollection 时才会跳过它。

public bool CompareEntities<T>(T oldEntity, T newEntity)
{
bool same = true;
PropertyInfo[] properties = oldEntity.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
.Where(pi => !(pi.PropertyType.IsSubclassOf(typeof(EntityObject)))
&& !(pi.PropertyType.IsSubclassOf(typeof(EntityReference)))
).ToArray();

foreach (PropertyInfo property in properties)
{
if (property.PropertyType.IsGenericType)
{
if (property.PropertyType.GetGenericTypeDefinition() == typeof(EntityCollection<>))
{
continue;
}
}

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

关于c#-4.0 - 获取实体对象的属性名称,不包括entitycollection和entityreference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8721555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com