I need Linq to sql queries with join and count - c#

i need to count how many singles of one matchmaker in tbluserregistration table.
i use following code,in this code if codition for filtering grid record.
please replay me fastly.
private IQueryable chanims
{
get
{
EntitiesModelMX dbContext = new EntitiesModelMX();
//var query = from p in dbContext.TblShadChanims
// where p.Confirmed == true || p.Status != null
// orderby p.ShadChanimID descending
// select p;
var query = from p in dbContext.TblShadChanims
join u in dbContext.TblUserRegistrations
on p.ShadChanimID equals u.ShadChanID into usercount
orderby p.ShadChanimID descending
select new
{
p,
Singles = usercount.Where(usr => usr.ShadChanID !=0).Count()
};
if (txtFirstNameFilter.Text.Trim().Length > 0)
{
query = (IOrderedQueryable<MainDataMX.TblShadChanim>)query.Where(p => p.p.FirstName.Contains(txtFirstNameFilter.Text.Trim()));
}
if (txtLastNameFilter.Text.Trim().Length > 0)
{
query = (IOrderedQueryable<MainDataMX.TblShadChanim>)query.Where(p => p.LastName.Contains(txtLastNameFilter.Text.Trim()));
}
if (txtPhoneFilter.Text.Trim().Length > 0)
{
query = (IOrderedQueryable<MainDataMX.TblShadChanim>)query.Where(p => p.Phone1.Contains(txtPhoneFilter.Text.Trim()));
}
if (!ddlStatus.SelectedValue.Equals("ALL"))
{
query = (IOrderedQueryable<MainDataMX.TblShadChanim>)query.Where(p => p.Status == (int?)int.Parse(ddlStatus.SelectedValue));
}
if (txtEmailFilter.Text.Trim().Length > 0)
{
query = (IOrderedQueryable<MainDataMX.TblShadChanim>)query.Where(p => p.Email.Contains(txtEmailFilter.Text.Trim()));
}
if (!drpGender.SelectedValue.Equals("ALL"))
{
query = (IOrderedQueryable<MainDataMX.TblShadChanim>)query.Where(p => p.IsMale == (bool?)bool.Parse(drpGender.SelectedValue));
}
return query;
}
}
above code is not working.please reply back.

just use Count with Grouping, please check the following links:
Group and count items
linq with groupby and count
Hope to be in use
:)

Related

Linq to SQL grouping with embedded lists causes too many queries

I am developing a query to grab and join some SQL tables in C# and am having some trouble with grouping and enumerables within the dataset. My query is below. This gives me the data in the format I'm looking for, but it takes way too long when I try to add the enumerated list as indicated below. When I look under the hood I can see it is executing way too many SQL queries. I'd like to get it to just one. Using LinqPad:
void Main()
{
var nightlyRuns = (from a in LoadTestSummaries
join b in LoadTestTestSummaryData
on a.LoadTestRunId equals b.LoadTestRunId
where a.TargetStack == "LoadEnv" &&
a.TestGuid != null &&
a.StartTime != null &&
a.LoadTestRunId != null
orderby a.StartTime
group new {a, b} by new
{
a.TestGuid,
a.Name,
a.Description,
a.StartTime,
a.Duration,
a.NumAgents,
a.NumHosts,
a.PassFail,
a.ResultsFilePath,
a.Splunk
}
into g
let scenarioStart = g.Min(s => s.a.StartTime) ?? g.Min(s => s.a.DateCreated)
let testCases = g.Select(s => s.b)
orderby scenarioStart
select new
{
TestGuid = g.Key.TestGuid,
ScenarioRun = new
{
Name = g.Key.Name,
Description = g.Key.Description,
StartTime = scenarioStart,
Duration = g.Key.Duration,
NumAgents = g.Key.NumAgents,
NumHosts = g.Key.NumHosts,
Result = g.Key.PassFail,
ResultsFilePath = g.Key.ResultsFilePath,
SplunkLink = g.Key.Splunk,
// PROBLEM: Causes too many queries:
TestRuns = from t in testCases select t.TestCaseId
}
}).ToLookup(g => g.TestGuid, g => g.ScenarioRun);
nightlyRuns["ba593f66-695f-4fd1-99c3-71253a2e4981"].Dump();
}
The "TestRuns" line is causing the excessive queries. Any idea what I am doing wrong here?
Thanks for any insight.
Tough answer to test but I think we can avoid the grouping and multiple queries with something like this: (https://msdn.microsoft.com/en-us/library/bb311040.aspx)
var nightlyRuns = (from a in LoadTestSummaries
join b in LoadTestTestSummaryData
on a.LoadTestRunId equals b.LoadTestRunId
where a.TargetStack == "LoadEnv" &&
a.TestGuid != null &&
a.StartTime != null &&
a.LoadTestRunId != null
into testGroup
select new
{
TestGuid = a.TestGuid,
ScenarioRun = new
{
Name = a.TestGuid,
Description = a.Description,
StartTime = a.StartTime ?? a.DateCreated,
Duration = a.Duration,
NumAgents = g.Key.NumAgents,
NumHosts = a.NumHosts,
Result = a.PassFail,
ResultsFilePath = a.ResultsFilePath,
SplunkLink = a.Splunk,
// PROBLEM: Causes too many queries:
TestRuns =testGroup
}
}).OrderBy(x=>x.StartTime).ToLookup(x => x.TestGuid, x => x.ScenarioRun);
nightlyRuns["ba593f66-695f-4fd1-99c3-71253a2e4981"].Dump();

Merge two Ordering Results into one result in linq with C#

I order two types of query. I want to show the result as one. if the first query and second query have count these both are merge and show the results of one. So i have created 3 list like jobs, jobs1, jobs2. I am getting values into jobs1 and jobs2. Then i have assigned using union into jobs3
Code
IQueryable<Job> jobs = _repository.GetJobs();
IQueryable<Job> jobs1 = _repository.GetJobs();
IQueryable<Job> jobs2 = _repository.GetJobs();
List<int> lstId = null;
List<int> lstUpdatedListId = null;
List<int> lstConId=null;
var order = _db.GetOrderDetails().Where(od => od.Masters.Id != null && od.OrderId == od.Master.OrderId && od.Master.Status == true && od.ValidityTill.Value >= currentdate).OrderByDescending(od => od.ValidityTill).Select(ord => ord.Master.Id.Value);
var order1 = _vasRepository.GetOrderDetails().Where(od => od.Masters.ConId != null && od.OrderId == od.Masters.OrderId && od.Masters.PaymentStatus == true && od.ValidityTill.Value >= currentdate).OrderByDescending(od => od.ValidityTill).Select(ord => ord.Masters.ConId.Value);
var updatedVacancyList = _repository.GetJobs().Where(c => c.UpdatedDate != null && updateFresh <= c.UpdatedDate).Select(c => c.Id);
if (order1 .Count() > 0)
{
lstConId = order1.ToList();
Func<IQueryable<Job>, IOrderedQueryable<Job>> orderingFunc = query =>
{
if (order1.Count() > 0)
return query.OrderByDescending(rslt => lstConId.Contains(rslt.Con.Id)).ThenByDescending(rslt=>rslt.CreatedDate);
else
return query.OrderByDescending(rslt => rslt.CreatedDate);
};
jobs1 = orderingFunc(jobs);
}
if (order.Count() > 0)
{
lstId = order.ToList();
lstUpdatedJobsListId = updatedVacancyList.ToList();
Func<IQueryable<Job>, IOrderedQueryable<Job>> orderingFunc = query =>
{
if (order.Count() > 0)
return query.OrderByDescending(rslt => lstId.Contains(rslt.Id)).ThenByDescending(rslt => lstUpdatedJobsListId.Contains(rslt.Id)).ThenByDescending(rslt=>rslt.CreatedDate);
if (updatedVacancyList.Count() > 0)
return query.OrderByDescending(rslt => lstUpdatedJobsListId.Contains(rslt.Id)).ThenByDescending(rslt => rslt.UpdatedDate);
else
return query.OrderByDescending(rslt => rslt.CreatedDate);
};
jobs2 = orderingFunc(jobs);
}
jobs = jobs1.Union(jobs2);
and i am getting an error while run the application as follows,
The text data type cannot be selected as DISTINCT because it is not comparable.
I need help to rectify this issue. I want to order in descending also.
One of your columns in Database is "Text" type. Convert it to varchar(MAX)

How can I filter a simple LINQ query and use it in a more complexe LINQ query

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

Select two columns from the table via linq

I use the query below to get all columns(20 more) in Entity Framework Linq. Because of out of memory exception, I only want to get two of them. One is "FileName", the other one is "FilePath". How to modify my code?
var query = DBContext.Table1
.Where(c => c.FacilityID == facilityID && c.FilePath != null && c.TimeStationOffHook < oldDate)
.OrderBy(c => c.FilePath)
.Skip(1000)
.Take(1000)
.ToList();
foreach(var t in query)
{
Console.WriteLine(t.FilePath +"\\"+t.FileName);
}
var query = DBContext.Table1.Where(c => c.FacilityID == facilityID && c.FilePath != null && c.TimeStationOffHook < oldDate)
.OrderBy(c => c.FilePath)
.Skip(1000)
.Take(1000)
.Select(c => new { c.FilePath, c.FileName })
.ToList();
foreach(var t in query)
{
Console.WriteLine(t.FilePath +"\\"+t.FileName);
}
You need to use Select.
Just select out two of the columns:
DBContext.Table1.Select(c => new { c.FileName, c.FilePath });
How about something like
using (var entity = new MyModel(ConnectionString))
{
var query = (from myTable in entity.theTable
where myTable.FacilityID == facilityID &&
myTable.FilePath != null &&
myTable.TimeStationOffHook < oldDate
orderby myTable.FilePath
select new
{
myTable,FileName,
myTable.FilePath
}).Skip(1000).Take(1000).ToList();
//do what you want with the query result here
}

LINQ: How can I shorten my code?

I have done some LINQ, it works great but I'm not a fan of this type of coding, I would like to shorten it down, but not quite sure how to.
Does anyone know how I can shorten this section of code? I've heard of predicates before but not quite sure how to implement them?
List<Voucher> list = new List<Voucher>();
if (String.IsNullOrEmpty(Search.SearchText) && Search.Status == 0)
{
list = (from voucherslist in db.Vouchers
//where voucherslist.Status != (int)VoucherStatus.Removed
select voucherslist)
.Take(100)
.ToList();
}
if (!String.IsNullOrEmpty(Search.SearchText) && Search.Status ==0)
{
list = (from voucherslist in db.Vouchers
where voucherslist.Title.Contains(Search.SearchText)
select voucherslist).Take(100).ToList();
}
if (String.IsNullOrEmpty(Search.SearchText) && Search.Status > 0)
{
list = (from voucherslist in db.Vouchers
where voucherslist.Status == Search.Status
select voucherslist).Take(100).ToList();
}
if (!String.IsNullOrEmpty(Search.SearchText) && Search.Status > 0)
{
list = (from voucherslist in db.Vouchers
where voucherslist.Status == Search.Status
&& voucherslist.Title.Contains(Search.SearchText)
select voucherslist).Take(100).ToList();
}
// Convert
ret = VouchersConverter.Convert(list);
// Get Business Details
foreach (ENT_Voucher item in ret)
item.BusinessDetails = this._businessesBLL.GetBusinessDataByID(item.BusinessID);
// Refine and sort
ret = ret.Where(x=>x.BusinessDetails.Accept == true)
.OrderByDescending(x => x.Status.Equals(1))
.ThenByDescending(x => x.StartDate).ToList();
To remove the repetition, first set up your list.
list = (from voucherslist in db.Vouchers
//where voucherslist.Status != (int)VoucherStatus.Removed
select voucherslist);
Then add the title search if you need it:
if (!String.IsNullOrEmpty(Search.SearchText))
{
list = list.Where(x => x.Title.Contains(Search.SearchText));
}
And the status search:
if (Search.Status > 0)
{
list = list.Where(x => x.Status == Search.Status);
}
And finally, take your 100 and flatten it to a list.
list = list.Take(100).ToList();
The thing to bear in mind is that this will not actually construct and execute the SQL query until the .ToList() call, and the SQL that will be executed will contain all of the filtering you have concatenated together.
Your current logic looks a bit broken to me, but I suspect you want:
var query = db.Vouchers;
if (...)
{
query = query.Where(v => v.Title.Contains(Search.SearchText);
}
if (...)
{
query = query.Where(v => v.Status == Search.Status);
}
// etc
List<Voucher> list = query.Take(100).ToList();
Using multiple calls to Where will effectively apply an "AND" on all the filters.

Categories