basic SQL to Linq question
-
Wednesday, April 04, 2012 5:22 PM
Hi, I am new to Linq. I am trying to convert the following sql statement to linq. but the syntax looks wrong. Please advise. Thanks
select Name, ID from Product var query = p in Product select p.Name, p.ID
All Replies
-
Wednesday, April 04, 2012 5:34 PM
Hi sdnd2000;
The query should be as follows:
var query = from p in DataContextInstanse.Product select new { p.Name, p.ID };
Fernando (MCSD)
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful". -
Wednesday, April 04, 2012 5:49 PM
Hi, Fernando:
Thanks for the help. It still reports error" Error 1 Cannot implicitly convert type 'AnonymousType#1' to 'BusinessApplication4.Web.Product' "
I attached the image, and I am using WCF RIA sercice.
-
Wednesday, April 04, 2012 6:08 PM
Hi sdnd2000;
What is the data type LoadOption?
What is Product class? Is it part of the DataContext or an independent class?
The reason for the exception is that the query is returning an anonymous type and you are trying to assign it to something of LoadOption<Product>, same reasoning that you can't assign a string to a integer data type.
If Product is not part of the DataContext can you post that class here.
Fernando (MCSD)
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful". -
Wednesday, April 04, 2012 6:15 PMYes, Product is part of employee domain context. So, for this situation, the get product query returns all the fields, but I just need 2 of them.
-
Wednesday, April 04, 2012 6:46 PM
Hi sdnd2000;
Well in a case like this the best option is to create a DTO, "Data Transfer Object", and return that to the layer using it. Something like the following:List<ProductDTO> query = (from c in edc.GetProductsQuery() select new ProductDTO() { Name = c.Name, ProductID = c.ProductID }).ToList(); public class ProductDTO { public string Name { get; set; } public int ProductID { get; set; } }
Fernando (MCSD)
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful". -
Wednesday, April 04, 2012 7:24 PM
still report error"Error 1 Cannot implicitly convert type 'BusinessApplication4.MainPage.ProductDTO' to 'BusinessApplication4.Web.Product'
-
Wednesday, April 04, 2012 7:58 PM
In the place you are running the query, BusinessApplication4.MainPage now has an object called ProductDTO. Where you are using the result of the query, BusinessApplication4.Web you are assigning it to a data type Product. Two different data types can not be assigned to each other.Use ProductDTO in place of Product in the BusinessApplication4.Web.Fernando (MCSD)
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".- Marked As Answer by sdnd2000 Thursday, April 05, 2012 1:16 AM

