Use LINQ to Join on Multiple Fields - c#

How would I do this in LINQ?
SQL
Where tblAccounts.AccountCode = tblAccountAssociations.ChildCode
And tblAccountAssociations.AssociationType = "DS"
Here is my attempt. The problem seems to be with "assoc.AssociationType == "DS". Is it part of the join or the Where clause?
var customers =
from customer in context.tblAccounts
join assoc in context.tblAccountAssociations on customer.AccountCode equals assoc.ChildCode
where customer.AccountType == "S" and assoc.AssociationType == "DS"
orderby customer.AccountType
select new { Customer = customer, Assoc = assoc };
Thanks in advance

According to MSDN (http://msdn.microsoft.com/en-us/library/bb311043.aspx), you use "&&", not "and", to specify multiple conditions in the "where" clause.

var customers =
from customer in context.tblAccounts
join assoc in context.tblAccountAssociations on customer.AccountCode equals assoc.ChildCode
where customer.AccountType == "S" **&&** assoc.AssociationType == "DS"
orderby customer.AccountType
select new { Customer = customer, Assoc = assoc };

Yes, "and" should be "&&", but the answer to your question is that in Linq the predicate assoc.AssociationType == "DS is not part of the join.
In SQL you could make it part of a join statement
...
FROM tblAccounts c
INNER JOIN tblAccountAssociations a ON
c.AccountCode = a.ChildCode AND a.AssociationType == "DS"
...
but in Linq statments you just add it as a predicate, the way you did (apart from the "and" issue).
In SQL, in terms of execution plan (performance), it does not matter whether you add it to the JOIN phrase or put it into a separate WHERE condition.

Related

convert trans-sql to LINQ LEFT JOIN and Where Clause

How would you convert this trans-sql to LINQ?
I've tried it with the DefaultIfEmpty() but it seems to not be working for me.
Any help is appreciated.
SELECT s.Status
FROM EducationModule M
LEFT JOIN EducationModuleStatus S ON M.CourseID = S.CourseID
AND M.ModuleID = S.ModuleID
AND S.StudentID = '1506'
WHERE M.courseid = 2
Thanks in advance.
Joining on multiple columns in Linq to SQL is a little different.
You have to take advantage of anonymous types and compose a type for the multiple columns you wish to compare against, and under the sheet this will generate the type of join you are looking for.
var abcd = from tl in db.EducationModule
join s in db.EducationModuleStatus
on new { t1.CourseID, t1.ModuleID } equals new {s.CourseID, s.ModuleID}
into tl_s
where tl.CourseID == 2 AND s.StudentID == '1506'
from s in tl_s.DefaultIfEmpty()
select new
{
Status = s.Status
};

Can we use if statement in linq for deciding to join or not?

I want to include a table in some conditions in Linq.
I am looking for sth like this:
var query = from x in context.Messages
if(x.senderID != 0)
{
join et in context.ETs on x.senderID equals et.ID
}
where x.Getter == SSN
select new { x.id, x.message}
Is this kind of approach possible or do I have to write two different linq queries and then I will combine them?
var query = from a in context.Messages
join b in context.ETs
on a.senderID equals b.ID
into temp
from b in temp.DefaultIfEmpty()
where a.Getter == SSN
select new { a.id, a.message}

Multiple table linq query?

Could you help me translate this SQL query in Linq and Lambda expression.
SELECT * FROM User
JOIN UserIdentifier ON User.id = UserIdentifier.user_fk
JOIN UserPassword ON User.id = UserPassword.user_fk
WHERE UserIdentifier.identifier_value = "key" AND UserPassword.password = "1234"
I already wrote this
var query = from u in context.Users
join ui in context.UserIdentifiers on u.id equals ui.user_fk into Joined
from j in Joined.DefaultIfEmpty()
join up in context.UserPasswords on u.id equals up.user_fk into Joined2
from ???
select new { id = u.id, identifier = j.identifier_value, password = Joined2.???}
with help of http://paragy.wordpress.com/2010/11/18/multiple-joins-with-linq-and-lambda/
I'm not a happy user of linq. Actually I don't like linq because of this kind of request. This one is simple but when you try complex request linq is a nightmare. It's even worst with dynamic request. I always have problem with linq syntax and the web doesn't really help. I don't find a correct documentation to write queries.
I guess I'm not the first one to ask this question but all the documentation I found seems wrong or doesn't help me. This is a simple query and I don't find correct help. I'm still waiting someone prove me that link is not just another POC.
You're missing a where clause.
And your SQL joins are regular INNER JOINs, so you don't need these join ... into g from x in g.DefaultIfEmpty() -> that's how you do an equivalent of LEFT OUTER JOIN.
var query = from u in context.Users
join ui in context.UserIdentifiers on u.id equals ui.user_fk
join up in context.UserPasswords on u.id equals up.user_fk
where ui.identifier_value == "key" && up.password == "1234"
select new
{
id = u.id,
identifier = ui.identifier_value,
password = up.password
};

Left Join using Linq with condition

I am trying to create a left join with a condition in my C# code. I can write it in SQL Server, but I am having problems writing it as a lambda expression. Here is a rough part of my SQL Code:
Select x.RequestId, aud.DepartmentId
From Requests x
Left Join UserDepartment ud on x.AssignedToTeam = ud.DepartmentId and ud.User = 'Joe'
I know how to write the Left Join but am unfamiliar with how or if it is possible to add the condition.
I suspect you want something like this:
var query = from request in db.Requests
join department in db.UserDepartments
.Where(dep => dep.User == "Joe")
on request.AssignedToTeam equals department.DepartmentId
into departments
from dep in departments.DefaultIfEmpty()
select new { request.RequestId,
DepartmentId = dep == null ? null : (int?) dep.DepartmentId
};
(Obviously change how you want to handle the absence of a department ID if necessary.)
Check out the MSDN article: How to: Perform Left Outer Joins (C# Programming Guide)
var request = db.View.Join(
db.UserDepartment.Where(w=>w.User=="Joe"),
a=>a.AssignedToTeam,
b=>b.DepartmentId,
(a,b)=> new {View = a, UserDepartment = b});

using Case or if statment in LINQ?

I have a LINQ query (using with EF)
I have the following LINQ query. Kindly guide me how I can use case or if statement in this query.
var selectedResults=
from InvoiceSet in Invoices
join BookedAreasSet in BookedAreas
on InvoiceSet.InvoiceID equals BookedAreasSet.InvoiceID
join AreaSet in Areas on BookedAreasSet.AreaID equals AreaSet.AreaID
select new
{
InvoiceSet.InvoiceNumber,
InvoiceSet.Amount,
InvoiceSet.TotalDiscount,
InvoiceSet.GST,
InvoiceSet.PaymentDate,
InvoiceSet.ShoppingCentreID,
BookedAreasSet.BookedAreaID,
AreaSet.Name //Here I want to use Case/ If statment based on some other column
};
Please guide.
Thanks
You can do it like this but using ternary operator ?
var selectedResults=
from InvoiceSet in Invoices
join BookedAreasSet in BookedAreas
on InvoiceSet.InvoiceID equals BookedAreasSet.InvoiceID
join AreaSet in Areas on BookedAreasSet.AreaID equals AreaSet.AreaID
select new {InvoiceSet.InvoiceNumber,InvoiceSet.Amount,InvoiceSet.TotalDiscount,InvoiceSet.GST, InvoiceSet.PaymentDate,InvoiceSet.ShoppingCentreID,BookedAreasSet.BookedAreaID,
AreaSet.Name, YourColumn = AreaSet.YourColumnName == yourVariable ? "firstResult" : "other result?"}
You can combine multiple conditions this way.
AreaSet.YourColumnName == yourVariable ? "firstResult" :
AreaSet.YourColumnName == YoursecondVariable ? "Some result" : "Some
other result"

Categories

Resources