using Case or if statment in LINQ? - c#

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"

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't use ToString() in LINQ to Entities query

So I have the following code:
string searchQuery = collection["query"];
var srmas = (
from SRMAs in db.SRMAs
join SRMAStatus in db.SRMAStatus on SRMAs.Id equals SRMAStatus.Id
join PurchaseOrders in db.PurchaseOrders on SRMAs.PONumber equals PurchaseOrders.PONumber
join Suppliers in db.Suppliers on PurchaseOrders.SupplierID equals Suppliers.SupplierID
join SRMADetails in db.SRMADetails on SRMAs.Id equals SRMADetails.SRMAId
where ids.Contains(SRMAs.Status)
&&
(
searchQuery.Contains(PurchaseOrders.suppliersOrderNumber)
||
searchQuery.Contains(SRMAs.PONumber.ToString())
)
select new
{
SRMAs.Id,
SRMAs.PONumber,
SRMAs.CreatedOn,
Suppliers.SupplierName,
SRMAStatus.StatusName,
PurchaseOrders.PODate, PurchaseOrders.suppliersOrderNumber
}
).ToList();
Where searchQuery is a string variable.
I have to actually use IN clause ofr PONumber and for that purpose I am using Contains which gives error mentioned in title. How do I check non String values?
you could give SqlFunctions.StringConvert a shot, it'll marry you to sql server and requires .Net 4+
searchQuery.Contains(SqlFunctions.StringConvert((decimal)SRMAs.PONumber))
the function seems a little twitchy, when I was spinning up a sample I had to convert my int to a decimal to avoid a Ambigious Invoication build error.
One apporach would be to convert searchQuery to the numeric datatype that the PONumber is, and you are all set.
EF 4 does not support ToString() Method on queries. Either you need to update it to EF6 or you can use SqlFunctions.StringConvert function as follows.
string searchQuery = collection["query"];
var srmas = (
from SRMAs in db.SRMAs
join SRMAStatus in db.SRMAStatus on SRMAs.Id equals SRMAStatus.Id
join PurchaseOrders in db.PurchaseOrders on SRMAs.PONumber equals PurchaseOrders.PONumber
join Suppliers in db.Suppliers on PurchaseOrders.SupplierID equals Suppliers.SupplierID
join SRMADetails in db.SRMADetails on SRMAs.Id equals SRMADetails.SRMAId
where ids.Contains(SRMAs.Status)
&&
(
searchQuery.Contains(PurchaseOrders.suppliersOrderNumber)
||
searchQuery.Contains(SqlFunctions.StringConvert((double)SRMAs.PONumber))
)
select new
{
SRMAs.Id,
SRMAs.PONumber,
SRMAs.CreatedOn,
Suppliers.SupplierName,
SRMAStatus.StatusName,
PurchaseOrders.PODate, PurchaseOrders.suppliersOrderNumber
}
).ToList();

linq left join with where clause show all from left table regardless

Im struggling with some linq
I want everything from the CustomerDiscountGroups table, then join a column from another table. If the where condition shows ther are no CustomerDiscounts i still want it to show all the colums from CustomerDiscountGroups table, and state 0 for Discount_PC ( a decimal)
heres my attempt
from c in CustomerDiscountGroups
join d in CustomerDiscounts on c.ID equals d.Discount_ID into cd
from cdi in (from f in cd
where f.AccountNo == "test"
select f).DefaultIfEmpty()
select new
{
c.ID,
c.DisplayName,
c.Image,
c.Added,
c.Added_by,
c.Edited,
c.Edited_by,
//cdi.Discount_PC
}
DefaultIfEmpty will make cdi null, even though it is of the type CustomerDiscounts. You have to handle that situation in your select clause:
select new
{
c.ID,
c.DisplayName,
c.Image,
c.Added,
c.Added_by,
c.Edited,
c.Edited_by,
Discount_PC = cdi == null ? 0 : cdi.Discount_PC
}
It is a bit awkward to have to write out a ternary operator for it and in fact, in C#6 there will probably be a new short hand operator for this.

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});

Use LINQ to Join on Multiple Fields

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.

Categories

Resources