How do I use reflection to get a list of loaded properties of a disconnected EF object?
I can use
var targetProperty.GetValue(targetOb开发者_Go百科ject, null);
var isLoaded = ((System.Data.Objects.DataClasses.RelatedEnd)(propertyValue)).IsLoaded;
but this only works for collection properties. For single object property, it doesn't work well. It will give message
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
The code I use is similar to the following
IEnumerable<object> q;
using(var context = new InfosContext())
{
q = context.Person.Include("Father").Take(10).ToList();
}
foreach(var value in q)
{
var sourceProperties = value.GetType().GetProperties().ToList();
var singleProperties = sourceProperties.Where(i => i.PropertyType.AssemblyQualifiedName.StartsWith("TestProject.Models.Entities")).ToList();
foreach(var i in singleProperties)
{
var propertyValue = i.GetValue(value, null); // BOOM. Exception here.
if (propertyValue != null && ((System.Data.Objects.DataClasses.RelatedEnd)(propertyValue)).IsLoaded)
{
}
}
}
Any help would be greatly appreciated.
foreach(var i in singleProperties)
{
var reference = value.GetType().GetProperty(i.Name + "Reference");
var refValue = reference.GetValue(value, null);
var isLoaded = ((System.Data.Objects.DataClasses.EntityReference)(refValue)).IsLoaded;
if(isLoaded)
{
}
}
精彩评论