开发者

How to get a list of loaded EF4.0 properties of a disconnected object using reflection

开发者 https://www.devze.com 2023-02-12 13:12 出处:网络
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);

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)
  {
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消