How can I rewrite this SQL query in LINQ with a lambda expression?
SELECT
CO.*
FROM
COMPANY CO
WHERE
CO.ID = '5'
AND CO.ID <> (SELECT COMPANY_ID
FROM dbo.EMPLOYEE
WHERE USERNAME = 'ADMIN')
I tried the following code I think it is correct, but it is not working:
var obj1 = db.COMPANies
.Where(co => co.ID != co.EMPLOYEEs.SingleOrDefault(em => em.USERNAME == userName).COMPANY_ID && co.ID == iID);
Can you please help me?
Can I use
co.EMPLOYEEs.SingleOrDefault(em => em.USERNAME == userName).COMPANY_ID
inside the db.COMPANies.Where ??
I have read the question in: How do I write SELECT FROM myTable WHERE id = (SELECT) in Linq?
but it not help me.
EDIT :
Image table structure, Click here
Sorry for my bad english. Thanks!
I hope that you have objects of COMPANY table and EMPLOYEE table which will be having the data. On those objects, you can fire the below LINQ to achieve your results.
COMPANY.Select(x => x.Id == 5 && x.Id != EMPLOYEE.Where(z => z.USERNAME == "ADMIN").Select(g => g.COMPANY_ID).FirstOrDefault());
Don't forget to add using System.Linq;
Using lambda expression, you can try this
var comapaniesWhereUserIsAdmin = from e in db.EMPLOYEEs
where e.username='Admin'
select e.CompanyId;
var result = from c in db.Companies
where c.ID == iID && !comapaniesWhereUserIsAdmin.Contains(c.ID)
select c;
Related
I have the following parameters:
public object GetDataByProjectCostID(string employeeid, DateTime costdate, int id = 0)
And the query:
var projectCost = (from pc in db.ProjectCosts
where pc.ProjectCostID == id
where System.Data.Entity.DbFunctions.TruncateTime(pc.CostDate) == costdate.Date
join p in db.Projects
on pc.ProjectID equals p.ProjectID
join sct in db.SubCostTypes
on pc.SubCostTypeID equals sct.SubCostTypeID
join ct in db.CostTypes
on sct.CostTypeID equals ct.CostTypeID
select new
{
p.ProjectName,
ct.CostTypeName,
ct.CostTypeID,
sct.SubCostTypeName,
pc.ProjectID,
pc.ProjectCostID,
pc.SubCostTypeID,
pc.Amount,
pc.Quantity,
pc.Note,
pc.CreatedBy,
sct.Unit,
pc.CreateDate,
pc.CostDate,
pc.ProjectCostImage
}).ToList();
Now my question is how i can add optional parameter in query.
Suppose if id not existed in request then i need to skip the where clause
where pc.ProjectCostID == id
In sql we can use when clause for that but what for in LINQ?
Thanks in advance.
try this
where (( id==0 || pc.ProjectCostID == id)
&& System.Data.Entity.DbFunctions.TruncateTime(pc.CostDate) == costdate.Date)
I use this technique in LinQ with the LinQ fluent form, you can try this:
//Make id nullable
public object GetDataByProjectCostID(string employeeid, DateTime costdate, int? id)
{
var projectCost = (from pc in db.ProjectCosts
//This expression is evaluated only if id has a value
where (!id.HasValue || pc.ProjectCostID == id)
&& System.Data.Entity.DbFunctions.TruncateTime(pc.CostDate) == costdate.Date
join p in db.Projects
on pc.ProjectID equals p.ProjectID
join sct in db.SubCostTypes
on pc.SubCostTypeID equals sct.SubCostTypeID
join ct in db.CostTypes
on sct.CostTypeID equals ct.CostTypeID
select new
{
p.ProjectName,
ct.CostTypeName,
ct.CostTypeID,
sct.SubCostTypeName,
pc.ProjectID,
pc.ProjectCostID,
pc.SubCostTypeID,
pc.Amount,
pc.Quantity,
pc.Note,
pc.CreatedBy,
sct.Unit,
pc.CreateDate,
pc.CostDate,
pc.ProjectCostImage
}).ToList();
}
I have the following SQL query:
SELECT
table1.Id AS EinAusgangId,
table1.Ausgabedatum,
table1.Rueckgabedatum,
table1.WerkzeugId,
cpmWerkzeug.Name
FROM cpmEinAusgang AS table1
INNER JOIN cpmWerkzeug ON table1.WerkzeugId = cpmWerkzeug.Id
WHERE table1.Id = (SELECT MAX(Id) AS Expr1
FROM dbo.cpmEinAusgang
WHERE table1.WerkzeugId = WerkzeugId)
My aim is to convert the whole query into a LINQ statement for further use in a .Net Application. I already converted joined tables to LINQ but is it also possible to use a select in the where clause?
This is what I got so far, which gives me almost the same result as the SQL statement above, but has major errors when the table cpmEinAusgang contains more then one record for one cpmWerkzeug
using (var dbContext = new cpmEntities())
{
var werkzeuge = from w in dbContext.cpmWerkzeug
join e in dbContext.cpmEinAusgang
on w.Id equals e.WerkzeugId
where e.Rueckgabedatum == null
orderby w.Name
select w;
return werkzeuge.ToList();
}
Has anyone an idea how to achieve the above sql in linq?
Thanks for your help. :)
EDIT:solved (see below)
var werkzeugeImUmlauf = from w in dbContext.cpmWerkzeug
join e in dbContext.cpmEinAusgang
on w.Id equals e.WerkzeugId
where e.Id == dbContext.cpmEinAusgang.Where(x => x.WerkzeugId == e.WerkzeugId).Max(x => x.Id) select w;
This is the final solution. As mentioned by Mittal in his answer, it is possible to write a sub-query in LINQ.
Yes, you can write Sub Query in LINQ as well.
var werkzeuge = from w in dbContext.cpmWerkzeug
join e in dbContext.cpmEinAusgang
on w.Id equals e.WerkzeugId
where w.id = (dbContext.cpmEinAusgang.Max(x => x.id)) AND w.WerkzeugId = WerkzeugId
I have an EF query which gets products from the database.
var query = (from pPrice in db.ProductPricing
join prod in db.Products on pPrice.ProductID equals prod.ProductID
join productExt in db.ProductsExt on prod.ProductID equals productExt.ProductID into pExts
from prodExt in pExts.DefaultIfEmpty()
where (includeNonPublic || pPrice.ShowOnline == 1)
&& ((eventID.HasValue && pPrice.EventID == eventID) || (!eventID.HasValue && !pPrice.EventID.HasValue))
orderby prod.DisplayOrder
select new ProductPricingInfo()
{
Product = prod,
ProductPricing = pPrice,
ProductExtension = prodExt
});
I have a table where I can specify add-on products (products which can be bought once the parent item has been bought).
My query to fetch these add-on products is
var addOnProductsQuery = (from pa in db.ProductAddons
where pa.EventID == eventID && pa.StatusID == 1
select new { ProductID = pa.ChildProductId });
Now what I am trying to do is filter on the query variable to only return products which are not in the addOnProductsQuery result.
Currently I have
var addOnProducts = addOnProductsQuery.ToList();
query = query.Where(e => !addOnProducts.Contains(e.Product.ProductID));
But there is a syntax error on the Contains(e.Product.ProductID)) statement
Argument 1: cannot convert from int to anonymous type: int ProductID
Chetan is right in the comments, you need to select the integer from the object before using Contains.
You can do it in 2 ways:
First you could just take the integer initially:
var addOnProductsQuery = (from pa in db.ProductAddons
where pa.EventID == eventID && pa.StatusID == 1
select new pa.ChildProductId);
This should give int as type so you can use Contains later with no problem.
Second, if you want to keep the addOnProductsQuery unchanged:
var addOnProducts = addOnProductsQuery.Select(a => a.ProductID).ToList();
query = query.Where(e => !addOnProducts.Contains(e.Product.ProductID));
I am close but no cigar. In SQL I can use an ISNULL in my where clause but I can't seem to get it to pass in linq.
var q3 =(
from Prin in HR
.Where(Prin => (Prin.JobName == "Pricipal-Elementary") &&
(ASup =>((String.Compare(ASup.UnitName,null) >=0)&&
(String.Compare(ASup.UnitName ,"%Learning%"))
))
)
//WHERE Prin.JobName = 'Principal-Elementary'
//AND ISNULL(ASup.UnitName,'') LIKE '%Learning%'
//ORDER BY SchoolName
from ASup in HR
.Where(ASup => ASup.ADAccount == Prin.ChiefADAccount)
.DefaultIfEmpty()
from Sch in UnitToSchools
.Where(Sch => Sch.UnitCode == Prin.UnitCode)
.DefaultIfEmpty()
select new
{
SchoolName = Prin.UnitName
,SchoolId = Sch.SchoolDetailFCSId
,PrincipalID = Prin.ADAccount
,LComm = ASup.UnitName
,AreaSupId = Prin.ChiefADAccount
}
);
var xyz = (q3).ToList();
//Below is the correct query in SQL
SELECT Prin.UnitName AS SchoolName
, Sch.SchoolDetailFCSId AS SchoolId
, Prin.ADAccount AS PrincipalID
, ASup.UnitName AS LComm
, Prin.ChiefADAccount AS AreaSupID
FROM IP_F.dbo.HR Prin
LEFT OUTER JOIN IP_F.dbo.HR ASup
ON ASup.ADAccount = Prin.ChiefADAccount
LEFT OUTER JOIN IP_F.dbo.UnitToSchool Sch
ON Sch.UnitCode = Prin.UnitCode
WHERE Prin.JobName = 'Principal-Elementary'
AND ISNULL(ASup.UnitName,'') LIKE '%Learning%'
ORDER BY SchoolName
Any help would be appreciated. Apparently I can't use String.Compare on a lambda. So I am stuck...
Thanks in Advance.
This part of your query:
ISNULL(ASup.UnitName,'') LIKE '%Learning%'
would be written in LINQ as
(ASup.UnitName ?? '').Contains("Learning")
Have your tried something like?
(String.IsNullOrEmty(ASup.UnitName) ? string.Empty : ASup.UnitName).Contains("Learning")
I'm writing a linq query in query syntax and I'm wondering how to add another where clause.
Basically, I have the following:
var test = from t in MyDC.TheTable
where t.UserID == TheUserID
where t.DateDone.Date == TheDate.Date
select new MyModel {.....};
TheTable has a column called LinkedID and this column is also in another table called ColorStatus (a number between 1 and 10). I'm looking to write the where clause "where the LinkedID in the ColorStatus table is less than 7".
Thanks.
Just a suggestion on improving the statement you have. You can actually merge the two where conditions into a single one. && means "AND"
Where t.UserID == TheUserID && t.DateDone.Date = TheDate.Date
Your information "another table called ColorStatus" doesn't make sense here.
var test = from t in MyDC.TheTable
where t.UserID == TheUserID
&& t.DateDone.Date == TheDate.Date
&& t.LinkedID < 7
select new MyModel {.....};
Probably I didn't get your idea, here is an example of join may help you.
var test = from t in MyDC.TheTable
join x in MyDC.ColorStatus
on t.LinkedID == x.LinkedID
where t.UserID == TheUserID
&& t.DateDone.Date == TheDate.Date
&& x.AnotherField == 1
select new MyModel {.....};