C# 在实体上调用GetProperties时,如何避免返回某些属性和外部实体?
我正在打电话:C# 在实体上调用GetProperties时,如何避免返回某些属性和外部实体?,c#,entity-framework,C#,Entity Framework,我正在打电话: var properties = person.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); 这将返回我想要
var properties = person.GetType().GetProperties(BindingFlags.DeclaredOnly |
BindingFlags.Public |
BindingFlags.Instance);
这将返回我想要的,除了,它还返回一个我不想要的名为Updated的属性,但我可以很容易地忽略它。它还返回我不想包含的
CarReference
和Car
。如何排除这些字段?目前,我有一个排除属性的列表,如果名称与其中一个匹配,我只跳过它,但我希望它更通用,而不是硬编码“CarReference”
和“Car”
,例如我不知道这是否是您正在寻找的,但这里有一个片段可以帮助您。自动生成的实体框架“实体”类的某些属性有一些标准:
var flags=BindingFlags.Public | BindingFlags.Instance;
var destinationProperties=typeof(tdestinition).GetProperties(flags);
foreach(destinationProperties中的var属性)
{
变量类型=property.PropertyType;
//忽略引用属性(例如TripReference)
if(type.IsGenericType&&type.GetGenericTypeDefinition()==typeof(EntityReference))
{
// ...
}
//忽略导航属性(例如行程)
if(type.IsGenericType&&type.GetGenericTypeDefinition()==typeof(EntityCollection))
{
// ...
}
//忽略ID(标量)属性(例如TripID)
if(property.GetCustomAttributes(typeof(EdmScalarPropertyAttribute),false).Any())
{
// ..
}
使用PropertyType中列出的“Namespace”属性,以下语句将跳过外部实体:if(type.Namespace!=“System”)
那么,它怎么可能是“更通用的”-可以使用什么标准来确定哪些属性(而不是字段-区分两者很重要)你想返回,而你不想返回?@JonSkeet-我不确定是否有一些标志可以传递以避免返回,或者它们是否有某种基类型可以用来避免返回。PropertyInfo对象上的某些内容我可以不用硬编码就使用?我只是将其称为字段,我将更新帖子以显示属性。避免返回哪个?除了你不想包括
CarReference
或Car
…这些属性有什么特别之处?应该返回Bus
和BusReference
属性吗?你真的需要在这里提供更多的上下文。@JonSkeet-I最初尝试执行person.GetType().GetFields()
,但这没有返回任何结果。我希望不会,因为如果不指定绑定标志,您将只获得公共字段,通常不应该有公共字段。属性几乎肯定是正确的。
var flags = BindingFlags.Public | BindingFlags.Instance;
var destinationProperties = typeof(TDestination).GetProperties(flags);
foreach (var property in destinationProperties)
{
var type = property.PropertyType;
// Ignore reference property (e.g. TripReference)
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(EntityReference<>))
{
// ...
}
// Ignore navigation property (e.g. Trips)
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(EntityCollection<>))
{
// ...
}
// Ignore ID (edmscalar) property (e.g. TripID)
if (property.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false).Any())
{
// ..
}
using (var db = new Entities.YourEntities())
{
var originalObj = db.MyTable.FirstOrDefault();
foreach (var prop in originalObj.GetType().GetProperties())
{
var type = prop.PropertyType;
if (type.Namespace != "System")
continue;
var name = prop.Name;
var value = prop.GetValue(originalObj, null);
//your code here
}
}