gpt4 book ai didi

c# - 获取添加到 Entity Framework 6 的对象列表包含列表

转载 作者:太空宇宙 更新时间:2023-11-03 12:43:57 24 4
gpt4 key购买 nike

背景

我在 Entity Framework 中创建了对象图,其中任何给定的对象 A 都会有一个表 Ac 来跟踪它的变化。这些对象也可能相互连接,例如 A 是 1-many 到 B。这是一个示例图:

            A -> Ac
/ \
Bc <- B \
/ \
Cc <- C D -> Dc

我希望能够在某个时间点加载一个对象和特定的连接对象,方法是使用更改表来提取这些记录并应用它们。理想情况下,我希望能够使用或模仿 .Include来自 Entity Framework 的功能。

问题

拉出哪些对象已包含在 IQueryable 中并不像我想象的那么容易。看着 IQueryable<T>带有 T 的子对象 Include() -ed,我可以看到这些关系存储在某种 SpanArguments 中的对象property - 但这些都是内部类,并且尝试检索此信息有很多步骤。

这是我目前所拥有的:

    public static void LoadVersion<T>( this IQueryable<T> query, DateTime targetDateTime )
{
//grab the value of the "Arguments" property on query.Expression
//this has to be done through reflection because "Arguments" is not accessible otherwise
PropertyInfo argumentsPropertyInfo = query.Expression.GetType().GetProperties().FirstOrDefault( x => x.Name == "Arguments" );
dynamic argumentsPropertyValue = argumentsPropertyInfo.GetValue( query.Expression );

for (int i = 0; i < argumentsPropertyValue.Count; i++)
{
//This gets me a System.Data.Entity.Core.Objects.Span, but that class is internal
//In the watch, I can see span -> SpanList[0].Navigations[0] gives me the name of the class in the .Include()
// This is the value I need
dynamic span = argumentsPropertyValue[i].Value;

//So if I try to pull it out using the same reflection trick as before, I get
// a dynamic {System.Reflection.PropertyInfo[0]} (not a list, as you would normally expect),
// and accessing those values & methods makes the debugger exit without an exception
dynamic spanPropertyInfo = argumentsPropertyValue[i].Value.GetType().GetProperties();

//this makes the debugger exit without an exception
dynamic spanPropertyValue = spanPropertyInfo[0].GetValue(span);

//this also makes the debugger exit without an exception (with the above line commented out, of course)
dynamic spanPropertyValue2 = spanPropertyInfo.GetValue( span );
}
}

基于我很难找到包含在查询中的内容,我不禁认为我这样做完全是错误的。深入研究 Entity Framework 6.1.3 的一些源代码并未对此有太多了解。

编辑

我一直在研究 Alex Derck 提供的代码,但我意识到我仍然需要一些代码才能按照我想要的方式完成这项工作。

这是 VisitMethodCall 的版本我实现了:

protected override Expression VisitMethodCall( MethodCallExpression node )
{
if (node.Method.Name != "Include" && node.Method.Name != "IncludeSpan") return base.VisitMethodCall(node);

try
{
string includedObjectName = (string) node.Arguments.First().GetPrivatePropertyValue( "Value" );

if (includedObjectName != null)
{
_includes.Add(includedObjectName);
}
}
catch (Exception e ){ }
return base.VisitMethodCall( node );
}

我能够使用包含构建查询并使用 IncludeVisitor 获取我包含的对象的名称,但使用这些的主要目标是能够找到相关表并将它们添加到包含。

所以当我有这样的等价物时:

var query = ctx.Persons.Include(p => p.Parents).Include(p => p.Children);
// includes[0] = "Parents"
// includes[1] = "Children"
var includes = IncludeVisitor.GetIncludes(query.Expression);

我成功抢到了includes ,然后我可以找到相关表(Parents -> ParentsChanges,Children -> ChildrenChanges),但我不是 100% 确定如何将这些添加回包含。

这里的主要问题是当它是嵌套语句时: context.A.Include(x => x.B).Include(x => x.C).Include(x => x.B.Select(y => y.D))

我可以成功遍历整个图并获得 A、B、C 和 D 的名称,但我需要能够添加这样的语句返回到包含:

[...].Include(x => x.B.Select(y => y.D.Select(z => z.DChanges)))

我可以很好地找到 DChanges,但我不知道如何构建包含备份的内容,因为我不知道 DChanges 和原始项目 (A) 之间有多少步骤。

最佳答案

source code 中查看了一下之后我注意到 Entity Framework 的包含不是 Expression 的一部分,而是 IQueryable 的一部分。如果你考虑一下,很明显它应该是那样的。表达式本身不能实际执行代码,它们由提供者翻译(这也是 IQueryable 的一部分),并非所有提供者都应该知道如何翻译 Include方法。在源代码中,您可以看到 IQueryable.Include 方法调用了以下小方法:

public ObjectQuery<T> Include(string path)
{
Check.NotEmpty(path, "path");
return new ObjectQuery<T>(QueryState.Include(this, path));
}

查询(转换为 ObjectQuery)只是被返回并且只有它的内部 QueryState 被改变,表达式没有任何变化。在调试器中,如果您查看 IQueryable,您可以看到将包含的 EntitySet,但我无法将它们放入列表(_cachedPlan 始终当我尝试通过反射访问它时为 null)。

enter image description here

我认为在看到这个之后,你试图做的事情是不可能的,所以我会在我的 dbContext 中保留一个静态字符串列表并实现一个自定义的 Include 扩展方法:

public partial class TestDB
{
public static ICollection<Expression> Includes { get; set; } = new List<Expression>();

public TestDB() : base()
{
Includes = new List<Expression>();
}

...
}

public static class EntityExtensions
{
public static IQueryable<T> CustomInclude<T, TProperty>(this IQueryable<T> query,
Expression<Func<T,TProperty>> include) where T : class
{
TestDB.Includes.Add(include);

return query.Include(include);
}
}

您还可以“覆盖”System.Data.Entity 中的普通Include 方法。我说“覆盖”,因为从技术上讲,实际上不可能覆盖扩展方法,但您可以自己创建一个名为 Include 的扩展方法,如果您不包含 >System.Data.Entity 在您使用它的地方,您自己的方法与来自 System.Data.Entity 的方法之间没有歧义:

public static class EntityExtensions
{
public static IQueryable<T> Include<T, TProperty>(this IQueryable<T> query,
Expression<Func<T,TProperty>> include) where T : class
{
TestDB.Includes.Add(include);

var method = typeof(QueryableExtensions)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Where(m => m.Name == "Include")
.First(m => m.GetParameters().All(p => p.ParameterType.IsGenericType));
var generic = method.MakeGenericMethod(typeof(T), typeof(TProperty));

return (IQueryable<T>)generic.Invoke(query, new object[] { query, include });
}
}

关于c# - 获取添加到 Entity Framework 6 的对象列表包含列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37991078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com