How to perform LINQ left outer join using method syntax? - linq

Microsoft has this help page for performing a left outer join, however it's in linq query syntax. What's the equivalent to this, using method syntax?
http://msdn.microsoft.com/en-us/library/bb397895.aspx
For example, I have two enumerables:
class TA {string Name{get;}}
class TB {string Name{get;}}
Enumerable<TA> A;
Enumerable<TB> B;
The result I want is this:
var joined =
A.Select(a => new
{ left = a,
right = B.FirstOrDefault(b => b.Name == a.Name)
});
This gives me what I need with just select and (effectively) a nested select. Perhaps this isn't an actual left outer join...

I've used something like
var q = (from a in db.Item1Set
from b in db.Item2Set.Where(i2 => i2.Item1Id == a.Id).DefaultIfEmpty());

Related

Linq Left Outer Join Two Tables on Two Fields

How do I left outer join two tables on two fields in linq?
I have a sql:
select a.*, b.* from courselist as a
left outer join Summary as b
on a.subject = b.Subject and a.catalog =
b.Catalogno
where a.degree_id = 1
order by a.sequenceNo
Below is my linq query, but there is error underline "join", failed in the call to "Groupjoin". I don't know how to correct that.
var searchResults = (from a in db.courselist
join b in db.Summary on
new { a.subject,a.catalog } equals
new { b.Subject, b.Catalogno } into ab
where a.degree_id == 1
orderby a.degree_sequenceNo
from b in ab.DefaultIfEmpty()
select new
{
Courselist = a,
Summary = b
}
).ToList();
Thanks.
I've checked your code again,
I found it's fault
you just need to specify join parameters name like this:
new { suject = a.subject, catalog = a.catalog } equals
new { suject = b.subject, catalog = b.Catalogno } into ab
It seems you are missing the reference, the query doesn't have an error
try to use this:
using System.Linq;
The main issue when people start using LINQ is that they keep thinking in the SQL way, they design the SQL query first and then translate it to LINQ. You need to learn how to think in the LINQ way and your LINQ query will become neater and simpler. For instance, in your LINQ you don't need joins. You should use Associations/Navigation Properties instead. Check this post for more details.
There should be a relationship between courselist and Summary, in which case, you can access Summary through courselist like this:
var searchResults = (from a in db.courselist
where a.degree_id == 1
orderby a.degree_sequenceNo
select new {
Courselist = a,
Summary = a.Summary
}).ToList();
If there is no relationship between the two, then you should reconsider your design.

How do I outer join and group by in Entity framework Linq?

I'm having trouble getting my Linq statemnt to work when doing an outer join and a group by. Here's a SQL version of what I'm trying to accomplish:
select p.PRIMARY_KEY, min(p.EFFECTIVE_DATE), sum(IsNull(c.PAID_INDEMNITY, 0))
from PRMPOLCY p
left outer join CLMMAST c on p.PRIMARY_KEY = c.POLICY_NO
where p.UNDERWRITER_UID = 93
GROUP BY p.PRIMARY_KEY
Here's what I have in Linq (which doesn't work):
var result = from p in context.PRMPOLCies
join c in context.CLMMASTs on p.PRIMARY_KEY equals c.POLICY_NO into polClm
where (p.UNDERWRITER_UID == underwriter)
from grp in polClm.DefaultIfEmpty()
group grp by p.PRIMARY_KEY into g
select new PolicySummation()
{
PolicyNo = g.Key,
Incurred = g.Sum(grp => grp.PAID_INDEMNITY ),
EffDate = g.Min(grp => grp.PRMPOLCY.EFFECTIVE_DATE
};
Beating my head against the wall trying to figurwe this out!
Assuming you have a navigation property set up between PRMPOLCY and CLMMAST, you shouldn't need to specify the join explicitly. It's much easier to express most queries in linq without explicit joins, but rather treating your structures as a hierarchy. I don't know the specifics of your model property names, but I'd take a guess that something like this would work.
var result =
from p in context.PRMPOLCies
where (p.UNDERWRITER_UID == underwriter)
select new PolicySummation {
PolicyNo = p.PRIMARY_KEY,
Incurred = p.CLMASTs.Select(c => c.PAID_INDEMNITY).DefaultIfEmpty().Sum(),
EffDate = p.EFFECTIVE_DATE,
};
You need to include both your tables in the group clause like this:
group new { p, grp } by p.PRIMARY_KEY into g
Then in your Sum / Min
g.Sum(grp => grp.grp == null ? 0 : grp.grp.PAID_INDEMNITY )
g.Min(grp => grp.p.PRMPOLCY.EFFECTIVE_DATE)

Get data from multiple tables to an object with LINQ join

I am trying to get from 3 related tables by using LINQ. But when I use 2 joins, the result takes only elements getting from 2nd join. Here is my code:
var myAssList = mldb.Assigns
.Join(mldb.Lists,
a => a.list_id,
l => l.id,
(a, l) => new {
Assign = a,
List = l
})
.Where(a => a.Assign.assigned_to == "myname")
.Join(mldb.Elements,
li => li.List.id,
e => e.parent_server_id,
(li, e) => new {
Element = e
});
var jsonSerialiser = new JavaScriptSerializer();
var listListJson = jsonSerialiser.Serialize(myAssList);
this Json return only attributes from Element(e) and List(li). But I want to get also the attributes from Assign(a).
The SQL query I am trying to realize in LINQ is that:
select * from Assigns
inner join Lists
on Assigns.server_list_id=Lists.id
inner join Elements
on Lists.id=Elements.parent_id
where Assigns.assigned_to='myname'
So, how can I get the attributes from the first join also (from "a", "l" and "e")?
You can access Assign entity from outer sequence li variable:
.Join(mldb.Elements,
li => li.List.id,
e => e.parent_server_id,
(li, e) => new {
Element = e,
Assign = li.Assign // here
});
from a in mldb.Assigns
join l in mldb.Lists on a.list_id equals l.id
join e in mldb.Elements on l.id equals e.parent_server_id
where a => a.Assign.assigned_to == "myname"
select new { Assign = a, Element = e }
This is so called "query syntax". It makes LINQ expressions looks like SQL queries.
In the end they are translated to IEnumerable extension methods. If you want
to join multiple tables then query syntax is more readable. Another useful feature
of query syntax is let clause. With the aid of it, you can declare additional variables
inside your queries.

nHibernate 3 - Left Join re-Linq solution

I am trying to to run this Linq query below with nHibernate 3.
var items = from c in session.Query<tbla>()
join t in session.Query<tblb>() on c.Id equals t.SomeId into t1 // use left join on trades.
from t2 in t1.DefaultIfEmpty()
select new {item = c, desc = t2.Description};
This is the stock way to perform a left join in linq to my knowledge. However it's giving me an unsupported exception message. How can I achieve a basic left join without resorting back to HQL? This seems somewhat silly that an ORM as prevalent as nHibernate cannot support something as pedestrian as a left join.
[edit]
I've put the real answer to my own question below.
After further research on this; this is possible (although not obvious) to achieve in a strongly typed fashion using QueryOver. The trick is to use outer Query alias variables in conjunction with WithAlias, and TransformUsing. Here is an example that does left join with filtering and sorting.
// Query alias variables
entityTypeA anchorType = null;
entityTypeB joinedType = null;
var items = session.Query<entityTypeA>( ()=>anchorType )
.Left.JoinAlias(() => anchorType.FieldName, () => joinedType)
.WithSubquery.WhereProperty(e => e.FieldD).In(myFilterList)
// bind property mappings using WithAlias
.SelectList(list => list
.Select(e => e.FieldNameA).WithAlias( ()=> anchorType.FieldNameA )
.Select(e => e.FieldNameB).WithAlias( ()=> anchorType.FieldNameB )
)
.OrderBy(e => joinedType.FieldNameC).Desc
.TransformUsing(Transformers.AliasToBean<entityTypeA>()) // transform result to desired type.
.List<entityTypeA>();
It's not supported yet. HQL is your only choice at the moment.

Greater Than Condition in Linq Join

I had tried to join two table conditionally but it is giving me syntax error. I tried to find solution in the net but i cannot find how to do conditional join with condition. The only other alternative is to get the value first from one table and make a query again.
I just want to confirm if there is any other way to do conditional join with linq.
Here is my code, I am trying to find all position that is equal or lower than me. Basically I want to get my peers and subordinates.
from e in entity.M_Employee
join p in entity.M_Position on e.PostionId >= p.PositionId
select p;
You can't do that with a LINQ joins - LINQ only supports equijoins. However, you can do this:
var query = from e in entity.M_Employee
from p in entity.M_Position
where e.PostionId >= p.PositionId
select p;
Or a slightly alternative but equivalent approach:
var query = entity.M_Employee
.SelectMany(e => entity.M_Position
.Where(p => e.PostionId >= p.PositionId));
Following:
from e in entity.M_Employee
from p in entity.M_Position.Where(p => e.PostionId >= p.PositionId)
select p;
will produce exactly the same SQL you are after (INNER JOIN Position P ON E..PostionId >= P.PositionId).
var currentDetails = from c in customers
group c by new { c.Name, c.Authed } into g
where g.Key.Authed == "True"
select g.OrderByDescending(t => t.EffectiveDate).First();
var currentAndUnauthorised = (from c in customers
join cd in currentDetails
on c.Name equals cd.Name
where c.EffectiveDate >= cd.EffectiveDate
select c).OrderBy(o => o.CoverId).ThenBy(o => o.EffectiveDate);
If you have a table of historic detail changes including authorisation status and effective date. The first query finds each customers current details and the second query adds all subsequent unauthorised detail changes in the table.
Hope this is helpful as it took me some time and help to get too.

Resources