Have been working mainly on java and new to LINQ so I need some suggestion regarding performance of this query .I have 3 tables
1. Products --> ProductID | Name | Price | VendorID
2. Category --> CategoryID | Label
3. SubCategory--> SubCategoryID | Label | ParentID
4. Product_SubCategory_Mapping--> ProductID | SubCategoryID
5. Vendor --> VendorID | VendorName
I want to select all products from product table along with its Vendors for any given subcategory .Should following query work fine ? Or it needs any optimization ?
var list = (from p in Products
join cat in Product_SubCategory_Mapping
on p.UserId equals cat.UserId
join sub in SubCategories
on cat.SubCategoryId equals sub.SubCategoryId
where sub.CategoryId == 19 && CustomFunction(p.ID) > 100
select new { p, p.Vendor, trend = CustomFunction(p.ID) })
.Skip((pageNum - 1) * pageSize)
.Take(pageSize);
I will be creating a custom class that will match result of query .
- Is creating a view/Stored procedure a better scenario in case like this ?
- Can CustomFunction(p.ID)>100 be named so function is not called twice ? Its a custom function in Database.
- For paging will Skip and take perform well ?
You’re on the right track, but LINQ to SQL won’t understand
CustomFunction()so you’ll need to switch to LINQ to Objects withAsEnumerable()before you can call it. You can also useletto capture the result ofCustomFunction()once for use elsewhere in the query:Update: To answer your listed questions:
letabove.Skip()andTake()on anIQueryable<>(likelistFromSqlabove) will translate into the appropriate SQL, limiting the result set sent across the wire.Skip()andTake()on anIEnumerable<>just enumerate the sequence to get the requested results, but operate on the full result set returned from SQL.