sql Left join with linq lampda expression
I have a problem in making a left/right join with linq.
I have lets say
public class Customer
{
prop string CustomerId { get; set; }
prop string LanguageGuid { get; set; }
}
public class ReadOnlyCustomer
{
prop string CustomerId { get; set; }
prop string LanguageGuid { get; set; }
}
I have a lot of customers in the ReadonlyCustomer table. In my case I dont have all the customers in customer table. So I cant use the Join, i dont what the inner join. I need the left or right join.
var test = db.Customer.Join(db.ReadOnlyCustomer, p => p.CustomerId, o => o.CustomerId, (c, o) => new ReadOnlyCustomer() { CustomerId = c.CustomerId, LanguageGuid = o.LanguageGuid ?? c.LanguageGuid });
开发者_JS百科
At this point, I get a null pointer, because the query cant join on a null ref.
How can I do a left join equal to sql left join, where I get NULL for value that does not exist in the datasource.
This needs to be in lampda not comprehensing syntax like (from o in ....)
// dennis
You need to use GroupJoin
, sometimes in conjunction with a call to DefaultIfEmpty()
afterwards to give a single null value for the group. You can then use SelectMany()
to end up with one result per pair, noting that one of the values in the result may be null.
For example:
// Note: can only do a *left* join, so "bigger" table comes first
var test = db.ReadOnlyCustomer
.GroupJoin(db.Customer,
p => p.CustomerId,
o => o.CustomerId,
(p, os) => new { p, os = os.DefaultIfEmpty() })
// Each pair may have multiple os here
.SelectMany(pair => pair.os.Select(o => new { pair.p, o }))
// Flattened, but o may be null
.Select(pair => new ReadOnlyCustomer {
CustomerId = pair.p.CustomerId,
LanguageGuid = o != null ? o.LanguageGuid ?? p.LanguageGuid
: p.LanguageGuid
});
(Out of interest, why does this need to be in lambda syntax rather than as a query expression? Typically joins of all kinds are simpler to express in query expressions.)
精彩评论