Reputation: 11
I am writing a join query that produces an anonymous result set. My problem is that I don't know which data type should be returned from my function service and I tried to return object type but I don't know how to access the elements of result in my source code...
Here is my code:
public static IEnumerable<object> GetProductSalesInfoById(int id)
{
var query = from product in database.Products
join sales in database.SalesOrderDetails
on product.ProductID equals sales.ProductID
select new {Name = product.Name,OrderId = sales.SalesOrderID,TotalPrice = (sales.UnitPriceDiscount)*sales.OrderQty*sales.UnitPrice};
IEnumerable<object> result = query.ToList();
return result;
}
Upvotes: 0
Views: 64
Reputation: 11
crate one custom class like this
public partial class ResultClass
{
public string Name {get;set;}
public int OrderId {get;set;}
public double TotalPrice {get;set;}
}
public List<ResultClass> GetProductSalesInfoById(int id)
{
var query = from product in database.Products
join sales in database.SalesOrderDetails
on product.ProductID equals sales.ProductID
select new ResultClass {Name = product.Name,OrderId = sales.SalesOrderID,TotalPrice = (sales.UnitPriceDiscount)*sales.OrderQty*sales.UnitPrice};
return result.ToList();
}
hope this will help you out.
Upvotes: 1
Reputation: 3018
You can use Tuple or anonymous type(you need to use casting to get back the object). Check this link for usage : Anonymous & tuple objects
Upvotes: 0
Reputation: 471
You should create a DTO class that contains the properties in your anonymous object and return an IEnumerable<T>
of it. Another not so good solution is to use dynamic
but I wouldn't use that.
Upvotes: 1