The .NET Standard Query Operators - emptyOrder - linq

In this msdn example:
The .NET Standard Query Operators
We see this example of a LEFT JOIN:
var custTotalOrders =
from c in customers
join o in orders on c.CustomerID equals o.CustomerID into co
from o in co.DefaultIfEmpty(emptyOrder)
select new { c.Name, o.OrderDate, o.Total };
And it says that:
where emptyOrder is an Order instance used to represent a missing order.
So, where does emptyOrder come from?
How can I use it in my code?

There are two overloads for DefaultIfEmpty
DefaultIfEmpty()
DefaultIfEmpty(defaultValue)
The first will return default(T) where T is the type contained in the enumerable when the enumerable is empty.
The second will return the value given in the defaultValue parameter when the enumerable is empty.
Assuming you declared emptyOrder like so:
Order emtpyOrder = new Order() { Total=100 };
Then in the query:
var custTotalOrders =
from c in customers
join o in orders on c.CustomerID equals o.CustomerID into co
from o in co.DefaultIfEmpty(emptyOrder)
select new { c.Name, o.OrderDate, o.Total };
When a customer did not have a matching order, the Total property in the projected anonymous object would have the value 100.

Related

Linq Contains The type arguments cannot be inferred

string[] companyIdsUnfiltered = companyIdsCsv.Split(',');
Up above my code and my error.
Link to bigger picture
The code is as follows:
string[] companyIdsUnfiltered = companyIdsCsv.Split(',');
var query = (from c in ctx.Companies
join co in ctx.Countries on c.CountryId equals co.Id
where companyIdsUnfilteres.Contains(c.Id)
select c.Id).ToArray();
Given the error I guess the solution is to cast c.Id to string.
var query = (from c in ctx.Companies
join co in ctx.Countries on c.CountryId equals co.Id
where companyIdsUnfilteres.Contains((string) c.Id)
select c.Id).ToArray();
Just to add, if casting to string is not possible, try c.Id.ToString() as well. And take care of nulls etc..

LINQ - using a query expression to calculate data time difference

I use EntityFramework 4, LINQ, and C#.
I need display data in a GridView from a query expression using Linq; I need project as anonymous type a value calculate on fly DateTime.UtcNow - cl.DateLocked Note: cl.DateLocked is of type DateTime and I need to know how many days of difference between this two dates.
With this query I receive an error:
DbArithmeticExpression arguments must have a numeric common type.
Any idea how to do it in Linq? If Linq does not allow it how to do it in a different way?
Thanks for your time
var queryContentsLocked = from cl in context.CmsContentsLockedBies
join cnt in context.CmsContents
on cl.ContentId equals cnt.ContentId
join u in context.aspnet_Users
on cl.UserId equals u.UserId
select new
{
cl.DateLocked,
cnt.ContentId,
cnt.Title,
u.UserName,
u.UserId,
TimePan = DateTime.UtcNow - cl.DateLocked // Problem here!!!
};
var queryContentsLocked = from cl in context.CmsContentsLockedBies
join cnt in context.CmsContents
on cl.ContentId equals cnt.ContentId
join u in context.aspnet_Users
on cl.UserId equals u.UserId
select new
{
cl.DateLocked,
cnt.ContentId,
cnt.Title,
u.UserName,
u.UserId,
Days = SqlFunctions.DateDiff("day", cl.DateLocked, DateTime.UtcNow)
};
Without using any SqlFunction
var grandTotalWork = (from t in db.AssignmentHandymandetails
join ad in db.AssignmentDetails on t.assignment_detail_id equals ad.assignment_detail_id
where ad.assignment_id == Convert.ToInt32(Label_assignmentId.Text)
select new { startTime = t.started_time.Value.TimeOfDay, endTime = t.end_time.Value.TimeOfDay, TotalWorkTime = (t.started_time.Value.TimeOfDay.Duration() - t.end_time.Value.TimeOfDay.Duration()).Duration()});
then you can bind the result in GridView you wish
Try this:
DateTime.UtcNow.Subtract(cl.DateLocked).TotalDays

Add Lambda Expression on Column to Linq .Where()

I have two tables, Orders and Customers, with Orders referencing Customers, and their mapped classes Order and Customer.
I want to write a method which receives a Linq Where() condition for both Orders and Customers:
void ProcessOrders(Expression<Func<Order, bool>> orderCondition,
Expression<Func<Customer, bool>> customerCondition)
{
var q = Database.Query<Order>().Where(orderCondition);
q = q.Where(o => o.Customer APPLY customerCondition); // how ?
... process records in q ...
}
Even after reading lots of SO answers on this topic and related articles on MSDN, it seems I cannot figure out how to apply the customer condition on the Order.Customer property.
(DB/ORM in use is Oracle/DevExpress, but I'm fine with a generic solution, so I did not include them in the tags. Please mention if your answer is restricted to a specific DB or ORM)
This is one way to achieve it.
void ProcessOrders(Expression<Func<Order, bool>> orderCondition,
Expression<Func<Customer, bool>> customerCondition>>)
{
var orders = Database.Query<Order>().Where(orderCondition);
var customers = Database.Query<Customer>().Where(customerCondition);
var q = from o in orders join c in customers on o.CustomerId == c.Id
select new {o, c}
}
Again, depending on the ORM, something like this may also work (I'm assuming a lazily loaded Customer.Orders collection property here):
void ProcessOrders(Expression<Func<Order, bool>> orderCondition,
Expression<Func<Customer, bool>> customerCondition>>)
{
var customers = Database.Query<Customer>().Where(customerCondition);
var q = from c in customers
let orders = c.Orders.Where(orderCondition)
select new {c, orders}
}
Any solution has to be tested against the specific linq provider, since different linq providers may or may not support certain queries...
You could try something like this:
var q = (from o in Database.Query<Order>().Where(orderCondition)
join c in Database.Query<Customer>().Where(customerCondition) on o.CustomerID equals c.CustomerID
select new { Order = o, Customer = c });

How to return specific list result from linq to entities

Hi Experts
I currenly write this code:
public IList<TResult> GetCustomQuery<TResult>(int orderID, Func<Order, TResult> selector)
{
using(RepositoryDataContext = new NorthwindEntities())
{
IList<TResult> res = (from od in RepositoryDataContext.Order_Details
join o in RepositoryDataContext.Orders
on od.OrderID equals o.OrderID
join p in RepositoryDataContext.Products
on od.ProductID equals p.ProductID
join c in RepositoryDataContext.Customers
on o.CustomerID equals c.CustomerID
where o.OrderID > orderID
select new
{
o.OrderID,
od.UnitPrice,
od.Quantity,
p.ProductName,
c.CompanyName
}).Select<Order, TResult>(selector).ToList();
}
}
I want to return result of my linq to entities in specific format(TResult).
writing this code using Lambda Expression is hard because of joins.
this line has exception :Select < Order, TResult > (selector)
how I can Fix that?
thanks
Instead of creating an Anonymous type, create a POCO or in your case an Order
select new Order()
{
OrderProperty1 = o.OrderID,
OrderProperty2 = od.UnitPrice,
OrderProperty3 = od.Quantity,
OrderProperty4 = p.ProductName,
OrderProperty5 = c.CompanyName
}).Select<Order, TResult>(selector).ToList();
In your second last line: Try to call ToList() before the Select(). Like this:
}).ToList().Select<Order, TResult>(selector);
Is it possible Iterate "res" and return a list of TResult?

LINQ .Count() not defined for int

I have the below LINQ statement, and get the error " 'int' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type 'int' could be found ( are you missing a using directive or assembly reference?) "
var queryFuture = from pqv in context.OrderPrintQueue_View
join od in context.Order_Details on pqv.confirmId equals od.ConfirmId
join pp in context.Product_Price on od.priceId equals pp.priceId
join p in context.Products on pp.productId equals p.ProductID
select new { p.stationId, inProc = 0, OrderLinesCount = od.recId.Count() };
od.recId.Count() is the portion that is returning an error. I'm very new to LINQ (have been using it for about 2 days) and am a novice programmer. The answers I have found all say to include the system.core assembly reference, and of course, the System.Linq using. I have all of those so I'm not sure what the deal is. I am using WPF with .NET 4, EF, and RIA services and the MVVM pattern.
recID is of type int, not IEnumerable<?>. Count() is only defined on IEnumerable<?>. You will ned a group by statement:
var queryFuture = from pqv in context.OrderPrintQueue_View
join od in context.Order_Details on pqv.confirmId equals od.ConfirmId
join pp in context.Product_Price on od.priceId equals pp.priceId
join p in context.Products on pp.productId equals p.ProductID
group od by od.recId into orders
select new { p.stationId, inProc = 0, OrderLinesCount = orders.Count() };
Note: I'm not sure of this combination of group by and join will work out, as I usually only use the method chains. You might have to adjust on the operators, however you'll need a group by in any case.
Why would you want to get the count for an integer? You are probably getting a single value back, not a collection, which it seems is what you are expecting.

Resources