如何将匿名类型转换为IQueryable< Order_Detail> ;? [英] How to cast an anonymous type to IQueryable<Order_Detail>?
问题描述
我正在创建一个OData
服务方法,在其中编写了以下代码:
I am creating an OData
service method in which I have written the following code:
[WebGet]
public IQueryable<Order_Detail> getByYear(int year)
{
var dc = new NorthwindBigEntities();
var query = from p in dc.Order_Details
where p.Order.OrderDate != null && p.Order.OrderDate.Value.Year == year
select new
{
TotalSales = p.UnitPrice * p.Quantity,
Product = p.Product.ProductName
};
return query;
}
但我遇到一个例外:
不能将类型'System.Linq.IQueryable AnonymousType#1'隐式转换为'System.Linq.IQueryable CustomMethod.Order_Detail'.
Cannot implicitly convert type 'System.Linq.IQueryable AnonymousType#1' to 'System.Linq.IQueryable CustomMethod.Order_Detail'.
我该怎么做?
推荐答案
代替select new
进行select p
.当前,您正在选择匿名对象,并且无法将其转换为System.Linq.IQueryable CustomMethod.Order_Detail
Instead of select new
do select p
. Currently you are selecting anonymous object and you can't convert it to System.Linq.IQueryable CustomMethod.Order_Detail
您无法投影到Order_Detail
,因为它似乎是一类框架.由于您正在匿名对象中进行计算,因此您可以按select p
返回IQueryable<Order_Detail>
并稍后在LINQ上对对象进行计算,也可以为该对象创建一个新类和项目.如果最终创建一个新类,则应按照类名称修改签名.
You can't project to Order_Detail
since it appears to be a class of framework. Since you are doing calculation in your anonymous object, You can either return IQueryable<Order_Detail>
by select p
and do the calculation later on LINQ to object, or you may create a new class and project to that. If you end up creating a new class then you should modify your signature as per class name.
public IQueryable<Order_Detail> getByYear(int year)
{
var dc = new NorthwindBigEntities();
var query = from p in dc.Order_Details
where p.Order.OrderDate != null && p.Order.OrderDate.Value.Year == year
select p;
return query;
}
如果您创建一个新的类,例如:
If you create a new class like:
public class MyClass
{
public string Product {get;set;}
public double TotalSales {get;set;}
}
那你就可以做
public IQueryable<MyClass> getByYear(int year)
{
var dc = new NorthwindBigEntities();
var query = from p in dc.Order_Details
where p.Order.OrderDate != null && p.Order.OrderDate.Value.Year == year
select new MyClass
{
TotalSales = p.UnitPrice * p.Quantity,
Product = p.Product.ProductName
};
return query;
}
考虑返回数据的服务,如果您创建自己的类并仅返回所需的属性,则更好.您还应该看到此问题
这篇关于如何将匿名类型转换为IQueryable< Order_Detail> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!