How can i convert a DBQuery<T> to an ObjectQuery<T>?

孤者浪人 提交于 2019-11-26 22:01:29

问题


I've got a DBQuery<T> which converts to an IQueryable<T> (this bit works fine). But then I'm trying to convert the IQueryable to an ObjectQuery .. which fails :-

public void Foo(this IQueryable<T> source)
{
    // ... snip ...

    ObjectQuery<T> objectQuery = source as ObjectQuery<T>;
    if (objectQuery != null)
    {
        // ... do stuff ...
    }
}

This used to work before I changed over to Entity-Framework 4 CTP5 Magic Unicorn blah blah blah. Now, it's not working - ie. objectQuery is null.

Now, DBQuery<T> inherits IQueryable<T> .. so I thought this should work.

If i change the code to ..

var x = (ObjectQuery<T>) source;

then the following exception is thrown :-

System.InvalidCastException: Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery1[Tests.Models.Order]' to type 'System.Data.Objects.ObjectQuery1[Tests.Models.Order]'.

Any suggestions?


回答1:


DbQuery<T> contains Include method so you don't need to convert to ObjectQuery. ObjectQuery is not accessible from DbQuery instance - it is wrapped in internal type InternalQuery and conversion operator is not defined.

Btw. when you add using System.Data.Entity and refrence CTP5 you will be able to call Include on IQueryable<T>!




回答2:


Using reflection, you can do this:

var dbQuery = ...;
var internalQueryField = dbQuery.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(f => f.Name.Equals("_internalQuery"));
var internalQuery = internalQueryField.GetValue(dbQuery);
var objectQueryField = internalQuery.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(f => f.Name.Equals("_objectQuery"));

// Here's your ObjectQuery!
var objectQuery = objectQueryField.GetValue(internalQuery) as ObjectQuery<T>;



回答3:


Not sure what you're trying to do with it, but would a dynamic variable help?

Using Type dynamic (C# Programming Guide)



来源:https://stackoverflow.com/questions/4766122/how-can-i-convert-a-dbqueryt-to-an-objectqueryt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!