I am trying to write a LINQ query that will get me some distinct values from two SQL Server data tables.
I have two tables named, Facility_Cost_TBL and Tenant_Bills_TBL.
I then have a column that is named Nursing_Home_Name which I am trying to get the distinct data from.
This is my effort in LINQ , however it does not work,
var name = (from f in dataContext.Facility_Cost_TBLs
join t in dataContext.Tenant_Bills_TBLs on f.Tenant_Code equals t.Tenant_Code
where f.Tenant_Code == code && f.Date_Month == date.Month && f.Date_Year == date.Year
select new {Facility_Cost_TBL = f, Tenant_Bills_TBL = t}).Distinct();
And this is a working SQL statement I made that does what I want via T-SQL.
SELECT DISTINCT Nursing_Home_Name
FROM (SELECT Nursing_Home_Name
FROM Facility_Cost_TBL
WHERE Date_Year = 2016 AND Date_Month = 10 AND Tenant_Code = 664250
UNION SELECT Nursing_Home_Name
FROM Tenant_Bills_TBL
WHERE Year_Data = 2016 AND Month_Data = 10 AND Tenant_Code = 664250)
a
Could someone show me what LINQ sytax AND what LINQ extension method query would look like?
Please try following
var names = ((from f in dataContext.Facility_Cost_TBLs
where f.Tenant_Code == "664250" && f.Date_Month == "10" && f.Date_Year == "2016"
select new { Nursing_Home_Name = f.Nursing_Home_Name }).
Union(
from t in dataContext.Tenant_Bills_TBLs
where t.Tenant_Code == "664250" && t.Date_Month == "10" && t.Date_Year == "2016"
select new { Nursing_Home_Name = t.Nursing_Home_Name })).ToList();
Hope this will help you
Try this to see if this works. LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?
var name = (from f in dataContext.Facility_Cost_TBLs
join t in dataContext.Tenant_Bills_TBLs equals on new { f.Tenant_Code, f.Date_Month, f.Date_Year } equals new { t.Tenant_Code, t.Date_Month, t.Date_Year }
where f.Tenant_Code == code && f.Date_Month == date.Month && f.Date_Year == date.Year
select new {Facility_Cost_TBL = f, Tenant_Bills_TBL = t}).Distinct();
i have this logic in one of my function but it does 3 roundtrips to the database. How can i convert the query to make only one query to the database?
var saisonTouristiqueId = 1;
var currentSaison = this.appContext.SaisonTouristiques.FirstOrDefault(x => x.SaisonTouristiqueId == saisonTouristiqueId);
var nextSaison = (from saison in this.appContext.SaisonTouristiques
where saison.DebutSaison > currentSaison.FinSaison
orderby saison.DebutSaison
select saison).FirstOrDefault();
if (nextSaison != null)
{
var forfaits = from forfait in this.appContext.Forfaits
where forfait.ComposantForfaits.Any(x => x.SaisonTouristiqueId == nextSaison.SaisonTouristiqueId)
select forfait;
return forfaits.ToList();
}
Only use FirstOrDefault when in the subsequent query, to allow all of the execution to be deferred.
var saisonTouristiqueId = 1;
var currentSaison = this.appContext.SaisonTouristiques
.Where(x => x.SaisonTouristiqueId == saisonTouristiqueId);
var nextSaison = from saison in this.appContext.SaisonTouristiques
where saison.DebutSaison > currentSaison.FirstOrDefault().FinSaison
orderby saison.DebutSaison
select saison;
var forfaits = from forfait in this.appContext.Forfaits
where forfait.ComposantForfaits.Any(x => x.SaisonTouristiqueId == nextSaison.FirstOrDefault().SaisonTouristiqueId)
select forfait;
return forfaits.ToList();
Hi i have the following code to select data from one table not in other table
var result1 = (from e in db.Users
select e).ToList();
var result2 = (from e in db.Fi
select e).ToList();
List<string> listString = (from e in result1
where !(from m in result2
select m.UserID).Contains(e.UserID)
select e.UserName).ToList();
ViewBag.ddlUserId = listString;
Am getting value inside listString .But got error while adding listString to viewbag.
Unable to cast object of type 'System.Collections.Generic.List`1[System.String]' to type 'System.Collections.Generic.IEnumerable`1[Main.Models.Admin.User]'.
First, could you update your question with the entire method so that we can see what might be going on with the ViewBag? Because your code should work just fine, assigning whatever value to the ViewBag is no problem normally:
ViewBag.property1 = 0;
ViewBag.property1 = "zero";
works just fine. ViewBag is dynamic. Now, you could get that error if you would later try to assing ViewBag.ddlUserId to something that actually is the wrong type.
I would like you to rewrite your statement as well, let me explain why. Assume for a moment that you have a lot ( > 100.000) of User records in your db.Users and we assume the same for Fi as well. In your code, result1 and result2 are now two lists, one containing >100.000 User objects and the other >100.000 Fi objects. Then these two lists are compared to each other to produce a list of strings. Now imagine the resource required for your web server to process this. Under the assumption that your actually using/accessing a separate SQL server to retrieve your data from, it would be a lot better and faster to let that server do the work, i.e. producing the list of UserID's.
For that you'd either use Kirill Bestemyanov's answer or the following:
var list = (from user in db.Users
where !db.Fi.Any(f => f.UserID == user.UserID)
select user.UserName).ToList()
This will produce just one query for the SQL server to execute:
SELECT
[Extent1].[UserName] AS [UserName]
FROM [dbo].[Users] AS [Extent1]
WHERE NOT EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Fi] AS [Extent2]
WHERE [Extent2].[UserID] = [Extent1].[UserID]
)}
which in the end is what you want...
Just to clarify more:
var list = (from user in db.Users
where !db.Fi.Any(f => f.UserID == user.UserID)
select user.UserName).ToList()
can be written as the following lambda expression as well:
var list = db.Users.Where(user => !db.Fi.Any(f => f.UserID == user.UserID))
.Select(user => user.UserName).ToList()
which from the looks of it is slightly different from Kirill Bestemyanov's answer (which I slightly modified, just to make it look more similar):
var list = db.Users.Where(user => !db.Fi.Select(f => f.UserID)
.Contains(user.UserID))
.Select(user => user.UserName).ToList();
But, they will in fact produce the same SQL Statement, thus the same list.
I will rewrite it to linq extension methods:
List<string> listString = db.Users.Where(e=>!db.Fi.Select(m=>m.UserID)
.Contains(e.UserID))
.Select(e=>e.UserName).ToList();
try it, it should work.
Try this it is very simple.
var result=(from e in db.Users
select e.UserID).Except(from m in db.Fi
select m.UserID).ToList();
var res = db.tbl_Ware.where(a => a.tbl_Buy.Where(c => c.tbl_Ware.Title.Contains(mtrTxtWareTitle.Text)).Select(b => b.Ware_ID).Contains(a.ID));
This mean in T-SQL is:
SELECT * FROM tbl_Ware WHERE id IN (SELECT ware_ID, tbl_Buy WHErE tbl_Ware.title LIKE '% mtrTxtwareTitle.Text %')
getdata = (from obj in db.TblManageBranches
join objcountr in db.TblManageCountries on obj.Country equals objcountr.iCountryId.ToString() into objcount
from objcountry in objcount.DefaultIfEmpty()
where obj.IsActive == true
select new BranchDetails
{
iBranchId = obj.iBranchId,
vBranchName = obj.vBranchName,
Addressline1 = obj.Addressline1,
Adminemailid = obj.Adminemailid,
BranchType = obj.BranchType,
Country = objcountry.vCountryName,
CreatedBy = obj.CreatedBy,
CreatedDate = obj.CreatedDate,
iArea = obj.iArea,
iCity = obj.iCity,
Infoemailid = obj.Infoemailid,
Landlineno = obj.Landlineno,
Mobileno = obj.Mobileno,
iState = obj.iState,
Pincode = obj.Pincode,
Processemailid = obj.Processemailid,
objbranchbankdetails = (from objb in db.TblBranchesBankDetails.Where(x => x.IsActive == true && x.iBranchId == obj.iBranchId)
select new ManageBranchBankDetails
{
iBranchId = objb.iBranchId,
iAccountName = objb.iAccountName,
iAccountNo = objb.iAccountNo,
iBankName = objb.iBankName,
iAccountType = objb.iAccountType,
IFSCCode = objb.IFSCCode,
SWIFTCode = objb.SWIFTCode,
CreatedDate = objb.CreatedDate,
Id = objb.Id
}).FirstOrDefault(),
objbranchcontactperson = (from objc in db.tblbranchcontactpersons.Where(x => x.Isactive == true && x.branchid == obj.iBranchId)
select new ManageBranchContactPerson
{
branchid = objc.branchid,
createdate = objc.createdate,
Id = objc.Id,
iemailid = objc.iemailid,
ifirstname = objc.ifirstname,
ilandlineno = objc.ilandlineno,
ilastname = objc.ilastname,
imobileno = objc.imobileno,
title = objc.title,
updateddate=objc.updateddate,
}).ToList(),
}).OrderByDescending(x => x.iBranchId).ToList();
getdata = (from obj in db.TblManageBranches join objcountr in db.TblManageCountries on obj.Country equals objcountr.iCountryId.ToString() into objcount from objcountry in objcount.DefaultIfEmpty() where obj.IsActive == true
select new BranchDetails
{
iBranchId = obj.iBranchId,
vBranchName = obj.vBranchName,
objbranchbankdetails = (from objb in db.TblBranchesBankDetails.Where(x => x.IsActive == true && x.iBranchId == obj.iBranchId)
select new ManageBranchBankDetails
{
iBranchId = objb.iBranchId,
iAccountName = objb.iAccountName,
}).FirstOrDefault(),
objbranchcontactperson = (from objc in db.tblbranchcontactpersons.Where(x => x.Isactive == true && x.branchid == obj.iBranchId)
select new ManageBranchContactPerson
{
branchid = objc.branchid,
createdate = objc.createdate,
Id = objc.Id,
iemailid = objc.iemailid,
}).ToList(),
}).OrderByDescending(x => x.iBranchId).ToList();
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));
I have the following SQL statement
SELECT [CodeHouse]
,[CodeReq]
,[Address]
FROM [ShahrdariProject].[dbo].[House]
where [CodeReq] in
(select [CodeReq] From [ShahrdariProject].[dbo].[HouseOwner] where [Name] = 'Alex' )
Can anyone please help me to convert this statement to LINQ?
This SQL:
SELECT [CodeHouse]
,[CodeReq]
,[Address]
FROM [ShahrdariProject].[dbo].[House]
where [CodeReq] in
(select [CodeReq] From [ShahrdariProject].[dbo].[HouseOwner]
where [Name] = 'Alex' )
Is equivalent to this Linq:
var q = from h in db.Houses
where db.HouseOwners.Any(x => x.Name == "Alex" && x.CodeReq == h.CodeReq)
select h;
using(var dbContext = new /**Your Linq DataContext class here**/())
{
var results = dbContext.House.Join(
dbContext.HouseOwner.Where(ho => ho.Name == "Alex"),
h => h.CodeReq,
ho => ho.CodeReq,
(h, ho) => select new { h.CodeHouse, h.CodeReq, h.Address }).ToArray();
}
EDIT: Based on your query, I figured it would be oK to express the query using a JOIN instead of using IN
List<string> codeReq = new List<string>();
using(DemoDataContext db = new DemoDataContext()){
var houses = from h db.Houses where codeReq.Contains(h.codeReq) selec h;
}
Try to use the following code, i am sure this resolve your issue
var result = from house in db.Houses
where db.HouseOwners.Any(z => z.Name == "Alex" && z.CodeReq == house.CodeReq)
select house;
Enjoy......