仅实体框架属性描述符集合字段值



。。嗨,我正在尝试连接来自任何实体的一些列值,如下所示:

var valor = "";
PropertyDescriptorCollection objProperties = TypeDescriptor.GetProperties(obj);

foreach (PropertyDescriptor objProperty in objProperties)
{
if (objProperty.Name != "AuditoriaUC" && objProperty.Name != "AuditoriaFC"
&& objProperty.Name != "AuditoriaIPC" && objProperty.Name != "AuditoriaUM"
&& objProperty.Name != "AuditoriaFM" && objProperty.Name != "AuditoriaIPM"
&& objProperty.Name != "AuditoriaEliminado")
{
valor = valor + " " + objProperty.Name + ": " + Convert.ToString(objProperty.GetValue(obj));
}
}
return valor;

但是,它也显示了列引用。换句话说,它也会在最后打印这个:

"ArchivosAdjuntos:System.Data.Objects.DataClasses.EntityCollection`1[XXX.MyProject.Model.Entities.ArchivosAdjuntos] 
CorrelativoActualPorPeriodo: XXX.MyProject.Model.Entities.CorrelativoActualPorPeriodo
CorrelativoActualPorPeriodoReference: System.Data.Objects.DataClasses.EntityReference`1[XXX.MyProject.Model.Entities.CorrelativoActualPorPeriodo] 
EntityState: Modified 
EntityKey: System.Data.EntityKey"

我只想返回列值,这可以通过将最后一个列值与硬编码字符串进行比较来打破foreach来实现。但我真的很想知道是否有更好的方法。

首先,您可以使用Type类的GetProperties方法,它允许一些过滤,比如只返回公共属性:

PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Public 
| BindingFlags.Instance);

然后可以使用LINQ来过滤引用类型属性。例如,您可以删除所有引用类型属性(字符串除外)并对其进行迭代:

var valueProps = props.Where(p => !p.PropertyType.IsClass 
|| p.PropertyType == typeof(string))
valueProps.ToList().ForEach(p => 
valor += p.Name + ": " 
+ (p.GetValue(obj) ?? "null"));

最后,对于那些使用硬编码列表排除的特性,可以将该硬编码的特性名称列表添加到上面的筛选表达式中。但是,您也可以考虑在要排除的字段上添加一个属性,并从属性列表中删除包括该属性的任何属性。这将是属性

[AttributeUsage(AttributeTargets.Property)]
public class ExcludeThisPropertyAttribute: Attribute
{
}

你可以把它设置在你的类上,比如

public class YourClass
{
public string PropertyThatIsIncluded { get; set; }
public int ThisIsIncludedToo { get; set; }
//more value type properties to be included ...
[ExcludeThisProperty]
public string AuditoriaUC { get; set; }
[ExcludeThisProperty]
public string AuditoriaFC { get; set; }
//more value type properties explicitly excluded ...
//reference type properties like this one will be automatically excluded
public CorrelativoActualPorPeriodo CorrelativoActualPorPeriodo { get; set; }
}

然后,提取值类型属性的表达式将被更新,以排除那些包含属性的表达式:

var valueProps = props.Where(p => 
p.GetCustomAttributes(typeof(ExcludeThisPropertyAttribute), true) == 0
&&(!p.PropertyType.IsClass 
|| p.PropertyType == typeof(string)))    

在您的情况下,似乎您使用的是实体框架,所以如果您的类是由EF生成的,为了能够设置属性的属性,您需要遵循类似于使用辅助元数据类的方法

最新更新