如何使用反射获取断开连接的对象的已加载 EF4.0 属性列表
如何使用反射来获取断开连接的 EF 对象的已加载属性列表?
我可以使用
var targetProperty.GetValue(targetObject, null);
var isLoaded = ((System.Data.Objects.DataClasses.RelatedEnd)(propertyValue)).IsLoaded;
,但这仅适用于集合属性。对于单个对象属性,它效果不佳。它会给出消息
ObjectContext 实例已 已处置且不能再用于 需要连接的操作。
我使用的代码类似于以下内容
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)
{
}
}
}
任何帮助将不胜感激。
How do I use reflection to get a list of loaded properties of a disconnected EF object?
I can use
var targetProperty.GetValue(targetObject, 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)