C# 为什么实体引用仍然包含在属性中是实现此代码的更好方法
正如您在下面看到的,我正在遍历实体的属性,以获取审计跟踪系统的字段名和值,但是它会返回对传递的对象的引用,即careerReference=system.Data.Objects.DataClasses.EntityReference`1 absanal=HallmarkSolutions.PAMS.Interop.EntityFramework.AbsenceSicknessReason 如何修改下面的代码以提高效率,同时忽略导航属性是C# 为什么实体引用仍然包含在属性中是实现此代码的更好方法,c#,winforms,entity-framework,C#,Winforms,Entity Framework,正如您在下面看到的,我正在遍历实体的属性,以获取审计跟踪系统的字段名和值,但是它会返回对传递的对象的引用,即careerReference=system.Data.Objects.DataClasses.EntityReference`1 absanal=HallmarkSolutions.PAMS.Interop.EntityFramework.AbsenceSicknessReason 如何修改下面的代码以提高效率,同时忽略导航属性是 public string ObjectToNotes
public string ObjectToNotes(object obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj", "Value can not be null or Nothing!");
}
StringBuilder sb = new StringBuilder();
Type t = obj.GetType();
PropertyInfo[] pi = t.GetProperties();
List<StandardLookup> absenceReasons = pamsContext.GetAbsenceReasons();
for (int index = 0; index < pi.Length; index++)
{
if (pi[index].PropertyType != typeof(EntityKey) && pi[index].PropertyType != typeof(EntityObject) && pi[index].PropertyType != typeof(EntityReference))
{
string message;
message = pi[index].Name.ToString() + " " + pi[index].PropertyType.ToString();
if (pi[index].Name=="reason")
sb.Append("reason=" + pamsContext.GetAbsenceReasonsDescription(Convert.ToInt32(pi[index].GetValue(obj, null))));
else
sb.Append(pi[index].Name + "=" + pi[index].GetValue(obj, null) + Environment.NewLine);
if (index < pi.Length - 1)
{
sb.Append(Environment.NewLine);
}
}
}
return sb.ToString();
}
公共字符串ObjectToNotes(objectobj)
{
if(obj==null)
{
抛出新ArgumentNullException(“obj”,“值不能为null或Nothing!”);
}
StringBuilder sb=新的StringBuilder();
类型t=obj.GetType();
PropertyInfo[]pi=t.GetProperties();
列出缺勤原因=pamsContext.getAbscenceReasons();
for(int index=0;index
首先,您可以忽略从EntityObject
派生的对象:
if (typeof(EntityObject).IsAssignableFrom(pi[index].PropertyType))
continue;
例如,这不会跳过AbsenceSicknessReasonId
属性(它只是一个Int32
属性,可能无法明显区别于另一个普通属性)。如果有一个非常天真的假设,您可能会做得更好一些:Id属性(几乎总是)有其相关的导航属性
if (pi[index].Name.EndsWith("Id"))
{
string navigationProperty =
pi[index].Name.Substring(0, pi[index].Name.Length - 2);
if (pi.FirstOrDefault(x => x.Name == navigationProperty) != null)
continue;
}
正如您所见,这是一个非常脆弱和幼稚的假设,但它在许多(大多数?)情况下都应该有效。您有实体上下文吗?如果是这样,您可以通过调用
List<string> propNames = context.Entry(yourEntry).OriginalValues.PropertyNames.ToList()
导航属性不包括在列表中
context.Entry(yourEntry).Property(propNames[0]).CurrentValue