SQL Query to ASP.NET LINQ Query - c#

What is the equivalent .NET LINQ Query for the below SQL Query?
select *
from customers
where CUSTOMERID not in ('123','321')

var exceptList = new List<string> {"123","321"};
var target = (from item in Db.customers select item.CUSTOMERID ).Except(exceptList);

from d in Members
where d.CUSTOMERID !=123 || d.CUSTOMERID !=321
select d

var ids=new[]{'123','321'};
var results= from x in Customers
where !ids.Contains(x)

For only those two values 123 and 321 you can simple do this:
var results = Customers.Where(c => c.CUSTOMERID != 123 && c.CUSTOMERID != 321);
For a list of values, something like nums where nums is an array of CUSTOMERID you can do this:
var nums = new int[]{123, 321};
var results = Customers.Where(c => !nums.Contains(c.CUSTOMERID));

Related

Get min and max value from database Linq to Sql query in MVC?

here is my query that i have written in my controller
public ActionResult Description()
{
var firstId = from p in obj.Cubisms
where p.Id = MIN(Id)
select p;
}
but here "MIN" or "Max" gives error what should be the query if i am wrong
You can use Enumerable functions to do the same,
var min = obj.Cubisms.Min(r=> r.Id);
var max = obj.Cubisms.Max(r=> r.Id);
var firstId = (from p in obj.Cubisms select p.Id).Min();
Try this:
var firstId = (from p in obj.Cubisms
orderby p.Id
select p).First();
Try this:
var firstId = (from p in obj.Cubisms select p.Id).Min();

Linq Dynamic Query With Group By

I need extra where clause for my Linq query. For example if customer choose a date filter so i need to date filter to my query etc... When i try to myQuery.Where predicate there is visible just group by's field.
How can i append new where condition to my query.
//for example i need dynamically append o.OrderDate==Datetime.Now or another where clause
var myQuery =(from o in _db.Orders
join l in _db.OrderLines.Where(x => x.ParaBirimi == model.ParaBirimi) on o.orderId equals
l.OrderId
where o.OrderDate.Value.Year == year1
group o by new {o.OrderDate.Value.Month}
into g
select
new
{
Month = g.Key.Month,
Total = g.Select(t => t.OrderLines.Sum(s => s.OrderTotal)).FirstOrDefault()
});
You are too late at the end of the query to add new Where. You have already grouped the data, and projected it, removing nearly all the fields.
Try:
var baseQuery = from o in _db.Orders
join l in _db.OrderLines.Where(x => x.ParaBirimi == model.ParaBirimi) on o.orderId equals l.OrderId
where o.OrderDate.Value.Year == year1
select new { Order = o, OrderLine = l };
if (something)
{
baseQuery = baseQuery.Where(x => x.Order.Foo == "Bar");
}
var myQuery = (from o in baseQuery
group o by new { o.Order.OrderDate.Value.Month }
into g
select
new
{
Month = g.Key.Month,
Total = g.Sum(t => t.OrderLine.OrderTotal)
});
Clearly you can have multiple if. Each .Where() is in && (AND) with the other conditions.
Note how the result of the join is projected in an anonymous class that has two properties: Order and OrderLine

How to use a SQL query "in" linq?

I have a SQL query like this:
SELECT [Id],[WfInstanceId]
FROM [WfTask]
WHERE DocId IN
(SELECT [Id]
FROM [FormInstance]
WHERE FormId = '91889C15-7205-4467-B626-3C4AAB22567B')
How can I use it with linq? I want to return an IQueryable and pass it to my grid view.
var q = from row in WfTast
where (from x in FormInstance
where FormId='91889C15-7205-4467-B626-3C4AAB22567B' &&
row.DocId = id
select x).Any()
select Id, WfInstanceId;
Or, with join:
var q = from Task in WfTast
join Form in (FormInstance.Where(x => x.FormId='91889C15-7205-4467-B626-3C4AAB22567B')
on Task.DocId = Form.Id
select Task.Id, Task.WfInstanceId;
or, Only flunet syntax:
var q = WfTast.Where(wt => FormInstance.Where(x => x.FormId='91889C15-7205-4467-B626-3C4AAB22567B' &&
wt.DocId = x.id).Any());
or:
var formsIdCollection = FormInstance.Where(x => x.FormId='91889C15-7205-4467-B626-3C4AAB22567B').Select(x => x.id);
// if you reuse this list, add at end this: .ToArray();
var q = from row in WfTast
where formsIdCollection.Contains(row.DocId)
select Id, WfInstanceId;
var query = DatabaseContext.WfTask.Where(
i => DatabaseContext.FormInstane
.Where(fi => fi.FormId = '...')
.Select(fi => fi.Id)
.Contains(i.DocId));

Sub-Query in linq

What is the best way to write this query in linq?
SELECT *
FROM product_master
where product_id in (select product_id from product where buyer_user_id=12)
var _result = from a in product_master
where (product.Where(s => s.buyer_user_id == 12))
.Contains(a.product_ID)
select a;
or
var _result = (from a in product_master
join b in product
on a.product_id equals b.product_id
where b.buyer_user_id == 12
select a).Distinct();
JW's answer is correct. Alternatively, given that the subquery is not correlated, you could express it separately:
var pids = product.Where(p => p.buyer_user_id == 12);
var r = product_master.Where(pm => pids.Contains(pm.product_id));

how to use Linq " NOT IN"

I'm using Entity Framework
So I want to write a sql command using two tables - tblContractor and tbSiteByCont tables.
It looks like this in SQL
SELECT PKConID, Fname, Lname
FROM tblContractor
WHERE (PKConID NOT IN
(SELECT FKConID
FROM tbSiteByCont
WHERE (FKSiteID = 13)))
but I don't know how to write in Linq.
I tried like this
var query1 = from s in db.tblSiteByConts
where s.FKSiteID == id
select s.FKConID;
var query = from c in db.tblContractors
where c.PKConID != query1.Any()
select Contractor;
But this doesn't work.
So how should I write it? What is the procedure? I'm new to Linq.
var _result = from a in tblContractor
where !(from b in tbSiteByCont
where FKSiteID == 13
select b.FKConID)
.Contains(a.PKConID)
select a;
or
var siteLst = tbSiteByCont.Where(y => y.FKSiteID == 13)
.Select(x => x.FKConID);
var _result = tblContractor.Where(x => !siteLst.Contains(x.PKConID));
I'd use a HashSet, it ensures you only evaluate the sequence once.
var result = from p in tblContractor
let hasht = new HashSet<int>((from b in tbSiteByCont
where b.FKSiteID == 13
select b.PKConID).Distinct())
where !hasht.Contains(p.PKConID)
select p;
may this work too
var _result = from a in tblContractor
.Where(c => tbSiteByCont
.Count(sbc => sbc.FKSiteID == 13 && c.PKConID == sbc.FKConID) == 0)

Categories