Sortorder in MVC ASP - sql-order-by

I have asp mvc and the output must be in order, first by Column and then by delivery point
var columnItems = stack.PriceLists
.OrderBy(p => p.ColumnOrder)
.OrderBy(p => p.DeliveryPoint.DeliveryPointId)
.Skip(5*n).Take(5);
The output however orders by deliverypoint. Please help?!?

Ah, it's easy! There is ThenBy, so I just replace the OrderBy and the ThenBy.

Related

Cosmos Db linq query for child item not working

I spent so many hours today on this without success, I hope someone can help me.
I'm trying Cosmos DB and LINQ, here the items in the db:
|Customer
|String Property1
|String Property2
|ICollection Orders
|String PropertyA <--Select on this property
How can I select the Item Customer which has the PropertyA with a specific value?
I tried this and so many other:
var customer = await context.Customers.Select(_s => _s.Orders.Select(p => p.PropertyA == "123456")).FirstAsync()
Thank you for your help.
EDIT 1:
I also tried this:
var customer1 = (from _customer in context.Customers
where _customer.Orders.Any(_a => _a.MyId.Contains("2012031007470165"))
select _customer).ToList();
Here the error message i received:
The LINQ expression 'DbSet()
.Where(c => EF.Property<ICollection>(c, "Orders")
.AsQueryable()
.Any(o => o.MyId.Contains("2012031007470165")))' could not be translated. Either rewrite the query in a form that can be translated,
or switch to client evaluation explicitly by inserting a call to
'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See
https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
If I understand your question properly
var customer = await ctx.Customers.Include(c => c.Orders).FirstAsync(s => s.Orders.FirstAsync(p => p.PropertyA == "123456"));
I found the solution, the right answer (use with cosmos SQL api and no more with Entity Framework) is:
Customer _customerResult = _DBcontainer.GetItemLinqQueryable<Customer>(true)
.Where(_w => _w.Orders.Any(c => c.Purchase_Id == "1234"))
.AsEnumerable()
.FirstOrDefault();

Entity Framework 4 - What is the syntax for joining 2 tables then paging them?

I have the following linq-to-entities query with 2 joined tables that I would like to add pagination to:
IQueryable<ProductInventory> data = from inventory in objContext.ProductInventory
join variant in objContext.Variants
on inventory.VariantId equals variant.id
where inventory.ProductId == productId
where inventory.StoreId == storeId
orderby variant.SortOrder
select inventory;
I realize I need to use the .Join() extension method and then call .OrderBy().Skip().Take() to do this, I am just gettting tripped up on the syntax of Join() and can't seem to find any examples (either online or in books).
NOTE: The reason I am joining the tables is to do the sorting. If there is a better way to sort based on a value in a related table than join, please include it in your answer.
2 Possible Solutions
I guess this one is just a matter of readability, but both of these will work and are semantically identical.
1
IQueryable<ProductInventory> data = objContext.ProductInventory
.Where(y => y.ProductId == productId)
.Where(y => y.StoreId == storeId)
.Join(objContext.Variants,
pi => pi.VariantId,
v => v.id,
(pi, v) => new { Inventory = pi, Variant = v })
.OrderBy(y => y.Variant.SortOrder)
.Skip(skip)
.Take(take)
.Select(x => x.Inventory);
2
var query = from inventory in objContext.ProductInventory
where inventory.ProductId == productId
where inventory.StoreId == storeId
join variant in objContext.Variants
on inventory.VariantId equals variant.id
orderby variant.SortOrder
select inventory;
var paged = query.Skip(skip).Take(take);
Kudos to Khumesh and Pravin for helping with this. Thanks to the rest for contributing.
Define the join in your mapping, and then use it. You really don't get anything by using the Join method - instead, use the Include method. It's much nicer.
var data = objContext.ProductInventory.Include("Variant")
.Where(i => i.ProductId == productId && i.StoreId == storeId)
.OrderBy(j => j.Variant.SortOrder)
.Skip(x)
.Take(y);
Add following line to your query
var pagedQuery = data.Skip(PageIndex * PageSize).Take(PageSize);
The data variable is IQueryable, so you can put add skip & take method on it. And if you have relationship between Product & Variant, you donot really require to have join explicitly, you can refer the variant something like this
IQueryable<ProductInventory> data =
from inventory in objContext.ProductInventory
where inventory.ProductId == productId && inventory.StoreId == storeId
orderby inventory.variant.SortOrder
select new()
{
property1 = inventory.Variant.VariantId,
//rest of the properties go here
}
pagedQuery = data.Skip(PageIndex * PageSize).Take(PageSize);
My answer here based on the answer that is marked as true
but here I add a new best practice of the code above
var data= (from c in db.Categorie.AsQueryable().Join(db.CategoryMap,
cat=> cat.CategoryId, catmap => catmap.ChildCategoryId,
cat, catmap) => new { Category = cat, CategoryMap = catmap })
select (c => c.Category)
this is the best practice to use the Linq to entity because when you add AsQueryable() to your code; system will converts a generic System.Collections.Generic.IEnumerable to a generic System.Linq.IQueryable which is better for .Net engine to build this query at run time
thank you Mr. Khumesh Kumawat
You would simply use your Skip(itemsInPage * pageNo).Take(itemsInPage) to do paging.

LINQTOSQL Help needed

I'm trying to add a column to the following LINQ expression. I want the column to contain a string concatenation of a text value in a many table called WasteItems. The join would be on "Waste.WasteId = WasteItem.WasteId". My problem is I need to display in a single dynamic column a string such as "EW (5); EX (3)" if there was 8 records in WasteItem and the column containing the 2 character string was called WasteItem.EWC. Hope that makes sense, there must be an efficient way since I realise LINQ is very powerfull. I'm new to it and not sure how to start or go about this:
return from waste in this._db.Wastes
where (from u in _db.UsersToSites.Where(p => p.UserId == userId && p.SystemTypeId == SystemType.W)
select u.SiteId)
.Contains(waste.SiteId)
orderby waste.Entered descending select waste;
THANKS IN ADVANCE
Something like this should do:
wastes.GroupJoin(db.WasteItems, w => w.WastId, wi => wi.WasteId, (w,wi) => new { w, wi })
.AsEnumerable()
.Select(x => new
{
x.w.Name,
Items = string.Join(", ", x.wi.GroupBy(wi => wi.EWC).Select(g => string.Format("{0} ({1})", g.Key, g.Count())))
})
Where wastes is the result from your query. The AsEnumerable() is necessary because Entity Framework can not handle string.Join, so that part must be dealt with in memory.
I could not check the syntax, obviously, but at least it may show you the way to go.

How do I merge two LINQ statements into one to perform a list2.Except(list1)?

Currently, I have the following LINQ queries. How can I merge the two queries into one. Basically, write a LINQ query to bring back the results I'd get from
IEnumerable<int> deltaList = people2010.Except(allPeople);
except in a single query.
var people2010 = Contacts.Where(x => x.Contractors
.Any(d => d.ContractorsStatusTrackings
.Any(date => date.StatusDate.Year >= 2010)))
.Select(x => x.ContactID);
var allPeople = Contacts.Where(x => x.Contractors
.Any(m => m.ContactID == x.ContactID))
.Select(x=> x.ContactID);
Thanks!
Why can you not just do Except as you are doing? Don't forget that your people2010 and allPeople variables are just queries - they're not the data. Why not just use them as they are?
If that's not acceptable for some reason, please give us more information - such as whether this is in LINQ to Object, LINQ to SQL etc, and what's wrong with just using Except.
It sounds like you're just looking for a more elegant way to write your query. I believe that this is a more elegant way to write your combined queries:
var deltaList =
from contact in Contacts
let contractors = contact.Contractors
where contractors.Any(ctor => ctor.ContractorStatusTrackings
.Any(date => date.StatusDate.Year >= 2010))
&& !contractors.Any(m => m.ContactID == contact.ContactID)
select contact.ContactID

How to write this linq query to avoid too many query?

I have two table Company and Employee. And there relation is Company(one) - Employee(many).
And I want to concatenate all the Employees' name to a string and output.
I know I can write such a query :
String names = "";
foreach(var emp in Company.Employee)
{
names += emp.name;
}
But If I use this mean, I would load all the employee records into memory, and then make comparison, which is a waste of time and memory, and would low the performance.
So in linq, is it possible to craft such a query that can return all concatenated names within a single SQL ?
Thanks in advance ! Any recommendations will be greatly appreciated !
var employeeNames = context
.Company
.Where(c => c.Id = 0xF00)
.SelectMany(c => c.Employee)
.Select(e => e.Name)
.ToArray();
var result = String.Join(" ", employeeNames);
You can vary the part of the query selecting the company a bit depending on the exact semantics and Entity Framework version. In .NET 4.0 the Entity Framework supports Single(). If you don't care about minor semantic differences you can use First() instead of SelectMany() prior to .NET 4.0.
This is a simplified variation of Daniel's but I think it should work (making assumptions about the schema)
var employeeNames = (from e in context.Employee
where e.CompanyId = 0xF00
select e.Name)
.ToArray();
var result = String.Join(" ", employeeNames);

Resources