问题
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;
}
but I am getting an exception:
Cannot implicitly convert type 'System.Linq.IQueryable AnonymousType#1' to 'System.Linq.IQueryable CustomMethod.Order_Detail'.
How can I accomplish this?
回答1:
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
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;}
}
Then you can do
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;
}
Considering its a service returning data, its better if you create your own class and return only the required properties. You should also see this question
来源:https://stackoverflow.com/questions/16734320/how-to-cast-an-anonymous-type-to-iqueryableorder-detail