In a previous question I asked how I would get a Customers first Order, it was answered thus :
var minOrders = from customer in DataSet.Customers
let order = (from o in DataSet.Orders where o.CustomerId == customer.CustomerId
order by o.OrderTimestamp
select o).first()
select new {
customer.Name,
order.OrderAmount
});
This is great, but how do I include a Left Outer Join onto the above? That is, return all Customers even if they have no orders, so something like :
var minOrders = from customer in DataSet.Customers LEFT OUTER JOIN
let order = (from o in DataSet.Orders where o.CustomerId == customer.CustomerId
order by o.OrderTimestamp
select o).first()
select new {
customer.Name,
order.OrderAmount
});
I know, in hindsight I should of asked this at the same time..
Thanks, Joe
Firstly, using let to do the join like this isn't ideal in the first place. There's a join clause in LINQ for a reason :)
Left outer joins aren't specifically supported in LINQ, but you can fake them like this:
var minOrders = from customer in DataSet.Customers
join order in DataSet.Orders.OrderBy(o => o.OrderTimestamp)
on customer.CustomerId equals o.CustomerId
into customerOrders
let order = customerOrders.FirstOrDefault()
select new {
customer.Name,
OrderAmount = order == null ? 0m : order.OrderAmount
};
Usually a left outer join uses from foo in bar.DefaultIfEmpty instead of let foo = bar.FirstOrDefault() but in this case you're only after the first match anyway, hence the different approach.
I'm pretty sure this works logically - whether the SQL translation will work or not is a different matter.
Related
this is a bit confusing for me. I know that left outer joins aren't built in to LINQ natively and that you have to use 'into' and 'DefaultIfEmpty()', but I have a bit of a complex SQL query.
The query:
SELECT * FROM TableA as a
LEFT OUTER JOIN TableB as b
on a.ID = b.ID and a.StatusOne = 1 AND b.StatusOne = 1 AND (a.StatusTwo != 1 OR b.StatusTwo!= 1)
LEFT OUTER JOIN TableC as c
on a.ID = c.ID AND a.StatusOne = 1 AND c.StatusOne = 1 AND (a.StatusTwo != 1 OR c.StatusTwo != 1)
WHERE
a.ID = 99999 AND (b.ID is not null OR c.ID is not null)
I'm not even really sure where to begin on this. If someone could help me out I would appreciate it immensely.
I am giving you the idea behind, I didn't tested the code, but to join two tables based on different fields, your join should have a anonymous type to compare.
var one = 1
from a in tableA
join b in tableB on new { a.ID, b.StatusOne } equals new { b.ID, one} into ab
But in your case you have more than one condition, so before calling DefaultIsEmpty, you should check the latest condition
from a in tableA
join b in tableB on new { a.ID, b.StatusOne } equals new { b.ID, one} into ab
from ab in ab.Where(x => x.a.StatusTwo != 1 || x.b.StatusTwo != one).DefaultIfEmpty()
Then the other outer join follows the same pattern and you need to make a final join. A good way to start is downloading the LinqPad and see which lambda expression it generates for your query, and you can take it from there. You can optimize it later but you will get the idea behind the generation. Hope this helps
I'm sorry for telling that I've a little bit weak on LINQ, I always do write SQL query before I start working on the complicated LINQ.
I want to ask that how to convert this SQL Query into LINQ with LEFT JOIN with multiple ON conditons with the OR operator.,
m.MerchandiseId will be use for twice in ON condition
SELECT
*
FROM
Inbox AS i
INNER JOIN [User] AS u ON i.FromUserId = u.UserId
LEFT OUTER JOIN Merchandise AS m ON
u.MerchandiseId = m.MerchandiseId
OR
i.ToMerchantId = m.MerchandiseId
WHERE
i.ToCompanyId = 10
OR
i.FromCompanyId = 10
var message = (from i in db.Inbox
join u in db.User on i.FromUserId equals u.UserId
join m in db.Merchandise on u.MerchandiseId equals m.MerchandiseId //here I want to ON i.MerchantId = m.MerchandiseId, but it doesn't allow
where i.ToCompanyId == user.CompanyId || i.FromCompanyId == user.CompanyId
orderby i.CreatedAt descending
group m.MerchandiseId by new { m.MerchandiseId, m.MerchandiseName } into grp
select new
{
MerchandiseId = grp.Key.MerchandiseId,
MerchandiseName = grp.Key.MerchandiseName,
InboxMessage = (from e in db.Inbox
join us in db.User on e.FromUserId equals us.UserId
join mer in db.Merchandise on us.MerchandiseId equals mer.MerchandiseId
where mer.MerchandiseId == grp.Key.MerchandiseId
orderby e.CreatedAt descending
select e.InboxMessage).FirstOrDefault(),
CreatedAt = (from e in db.Inbox
join us in db.User on e.FromUserId equals us.UserId
join mer in db.Merchandise on us.MerchandiseId equals mer.MerchandiseId
where mer.MerchandiseId == grp.Key.MerchandiseId
orderby e.CreatedAt descending
select e.CreatedAt).FirstOrDefault(),
}).ToList();
The bottom LINQ Query I've write for it. However, I just can work on the left join with multiple ON clause in LINQ. Appreciate if someone would help me on this. Thanks!
I don't believe Linq supports the use of the OR operator with multiple columns, but that said, I wouldn't use OR even in SQL as it makes the join's intention unclear and it also obscures where the data originated from - it also isn't immediately clear what happens if there are multiple matches for each column. Instead I would JOIN twice on the different columns and let the projection-clause handle it:
SELECT
*
FROM
Inbox
INNER JOIN [User] AS u ON i.FromUserId = u.UserId
LEFT OUTER JOIN Merchandise AS userMerchant ON u.MerchandiseId = userMerchant.MerchandiseId
LEFT OUTER JOIN Merchandise AS inboxMerchant ON Inbox.ToMerchantId = inboxMerchant .MerchandizeId
WHERE
Inbox.ToCompanyId = 10
OR
Inbox.FromCompanyId = 10
This can then be translated into Linq using the LEFT OUTER JOIN approach ( How to implement left join in JOIN Extension method )
Note that if you're using Entity Framework then you don't need to worry about doing any of this at all! Just use Include:
var query = db.Inbox
.Include( i => i.User )
.Include( i => i.User.Merchandise )
.Include i => i.Merchandise )
.Where( i => i.ToCompanyId = 10 || i.FromCompanyId == 10 );
Hi i am trying to join two tables in c#. the join code is given below. The problem is that when there is null value for tourid in tb_abc then in will not include that row from tb_abc in the list.
return (from p in context.tb_abc
from o in context.tb_Second
where o.id==p.tourId
where p.driverId == driverId
select new abcBean
{
id=p.id,
name=o.name
}).ToList<abcBean>();
Can anyone tell me what i am doing wrong
You are not doing an inner join in that query. You are doing a cross join, its where you have two tables and join each record to every other record.
If you want to include rows that return null on one of the constraints you need a left outer join.
return (from p in tb_abc
join o in tb_Second on p.tourId equals o.id into po
where p.driverId == driverId
from subpo in po.DefaultIfEmpty()
select new abcBean
{
id=p.id,
name=(subpo == null ? String.Empty : subpo.Name)
}).ToList();
Consider these two sql statements:
The first a cross join:
select id, name
from tb_abc o,
tb_Second p
where
o.id = p.tourID
and p.driverID = #driverID
The second a left outer join:
select id, name
from tb_abc o
LEFT OUTER JOIN tb_Second p on o.id = p.tourID
where
p.driverId = #driverID
The second will give you one set of the records, that include the null value of o.id.
The first will give you something of a Cartesian product which you rarely want.
Linq's DefaultIfEmpty() puts the default value (null) into the record if it doesnt find a match for the one side, so it behaves like the left outer join.
you can use left outer join like
return (from p in context.tb_abc
join o in context.tb_Second on o.id==p.tourId into gt
where p.driverId == driverId
from subsecond in gt.DefaultIfEmpty()
select new abcBean
{
id=p.id,
name=(subsecond == null ? String.Empty : subsecond.Name)
}).ToList<abcBean>();
The Linq-To-SQL that needs refactoring is found below:
var query = from p in Cache.Model.Products
join sc in Cache.Model.ShishaCombinations on p.ProductID equals sc.ProductID
where sc.NumberOfMixes == mixes
select new { p.ProductID, p.Name };
with the following one-liner:
group by p.ProductID
I know that group by omits any need for the select clause so both can live together in the same LINQ-To-SQL statement so can someone help me refactor the above please?
To help me remove any repeating data in my results. <-- This is the entire point in this question. A product is repeated a number of times based on the number of Flavours that are used by the product. So as a result in the 'ShishaCombinations' table one ProductID may be repeated many times one for each flavour that it uses. I would like to group the results returned from the query above or call distinct on it as I don't want add the product 'n' times to my GUI because it appears 'n' number of times in my results. Hopefully that will clear up any confusion of what I am trying to do.
The code below is all what I needed:
var query1 = (from p in Cache.Model.Products
join sc in Cache.Model.ShishaCombinations on p.ProductID equals sc.ProductID
where sc.NumberOfMixes == mixes
select new { p.ProductID, p.Name }).Distinct();
Ufuk, thanks for answering mate. I knew my answer was a simple one lol : )
You can use into keyword after select clause. You cannot just group by because you are projecting an anonymous type.
var query = from p in Cache.Model.Products
join sc in Cache.Model.ShishaCombinations on p.ProductID equals sc.ProductID
where sc.NumberOfMixes == mixes
select new { p.ProductID, p.Name } into productInfo
group productInfo by productInfo.productId;
var result = from R in db.Clients.Where(clientWhere)
join RA in db.ClientAgencies on R.SysID equals RA.SysID
join A in db.Agencies.Where(agencyWhere) on RA.AgencyID equals A.AgencyID
join AC in db.AdCommittees on A.AgencyID equals AC.AgencyID into temp
from x in temp.DefaultIfEmpty().Distinct()
select new {R,RA,x};
If user enters CommitteeID this is what I do, but I feel there has to be a better way.
var query = (from R in result
where R.x.CommitteeID == params.CommitteeID
select R.R).Distinct();
return query;
Is there a better way?
How are you using the data. The joins could be hurting you depending on what you're trying to achieve (which is very difficult for us to view without context of your data structures).
I can't fault the linq other than to say that you appear to have a log of data being joined which you may or may not need.
The other problem I have is that you will execute the query when you call DefaultIfEmpty(). This means to do your filter you may hit the database again to calculate it's result.
Could you provide some info on your DB Schema and what you are trying to get from your query?
If you're not using your intermediate query for anything else, I would flip it (filter by committeeID first):
Client GetCommitteeClient(int committeeID)
{
return (
from AC in db.AdCommittees
where AC.CommitteeID == committeeID
join A in db.Agencies.Where(agencyWhere) on AC.AgencyID equals A.AgencyID
join RA in db.ClientAgencies on A.AgencyID equals RA.AgencyID
join R in db.Clients.Where(clientWhere) on RA.SysID equals R.SysID
select R
).SingleOrDefault();
}