Hi i got question for the entity query. Please see my code
var list = from table in db.USER_BETTINGS
where table.UserID == UserId
&& table.UserID !="admin"
//&& table.WinningAfterRebate != 0m
&& table.BettingTransactionTime >= fromDate &&
table.BettingTransactionTime <= toDAte
//&& table.WinningAfterRebate !=0m
// orderby table.BettingTransactionNumber descending//table.BettingNumber descending//, table.BettingTransactionTime descending//
select table;
if (loteryNumber != 0)
{
list= list.Where(x => x.LotteryNumber == loteryNumber);
}
if (gameNum != 0)
{
list= list.Where(x => x.GameNumber == gameNum);
}
if (periodDate != "")
{
list= list.Where(x => x.PeriodDate == periodDate);
}
if (close.Equals("Y"))
{
list= list.Where(w => w.WinningAfterRebate != 0m);
}
else
{
list= list.Where(x => x.WinningAfterRebate == 0);
}
But the list not filtering , It return all record? Anyone got face this problem before?
You need some makeover in this code. You have unnecessarily used so many if condition, we need to get rid of that first. Change your query with the following.
var list =( from table in db.USER_BETTINGS
where table.UserID == UserId
&& table.UserID !="admin"
&& table.BettingTransactionTime >= fromDate
&& table.BettingTransactionTime <= toDAte
&& table.LotteryNumber == (loteryNumber != 0 ? loteryNumber : table.LotteryNumber)
&& table.GameNumber == (gameNum != 0 ? gameNum : table.GameNumber)
&& table.PeriodDate == (periodDate != string.Empty ? periodDate : table.PeriodDate )
&& (close.Equals("Y") ? table.WinningAfterRebate != 0 : table.WinningAfterRebate == 0)
).ToList();
Related
I have a table that I am filtering on. There is a four filters status, project, department, KPI
KPI is a boolean value. This filter has three value. True, False or both.
So, when the filter is true, it should return 'true' data, when the filter is 'false', return 'false' data; and when 'all' return both true and false data.
My code attached below, how can I enhance this code ? Can I write this with out if else conditions
var result = new List<TaskMaster>();
bool kpidata;
if (request.IsKPI == 1) { kpidata = true; } else { kpidata = false; }
//For KPI Tasks
if (request.IsKPI == 1 || request.IsKPI == 0)
{
result = await _context.TaskMaster.Where(c => c.IsActive && (c.Status == request.Status || request.Status == "All") && (c.ProjectId == request.ProjectId || request.ProjectId == 0) && (c.IsKPI == kpidata) && (c.AssignedTo.DepartmentId == request.DepartmentId || request.DepartmentId == 0)).Include(y => y.TaskActionLogs)
.Include(y => y.AssignedTo)
.Include(y => y.AssignedBy)
.Include(y => y.Project)
.AsSplitQuery().ToListAsync();
//For Non-KPI Tasks
}
else {
result = await _context.TaskMaster.Where(c => c.IsActive && (c.Status == request.Status || request.Status == "All") && (c.ProjectId == request.ProjectId || request.ProjectId == 0) && (c.AssignedTo.DepartmentId == request.DepartmentId || request.DepartmentId == 0)).Include(y => y.TaskActionLogs)
.Include(y => y.AssignedTo)
.Include(y => y.AssignedBy)
.Include(y => y.Project)
.AsSplitQuery().ToListAsync();
}
Revise the code, both queries are almost identical except c.IsKPI == kpidata part.
Few ways to remove the redundant:
Write the IQueryable query and append the .Where() if the condition meets. You are fine to append/extend the query before the query is materialized (via .ToList(), .First() etc.).
var result = new List<TaskMaster>();
bool kpidata;
if (request.IsKPI == 1) { kpidata = true; } else { kpidata = false; }
IQueryable<TaskMaster> query = _context.TaskMaster
.Where(c => c.IsActive
&& (c.Status == request.Status || request.Status == "All")
&& (c.ProjectId == request.ProjectId || request.ProjectId == 0)
&& (c.AssignedTo.DepartmentId == request.DepartmentId || request.DepartmentId == 0));
//For KPI Tasks
if (request.IsKPI == 1 || request.IsKPI == 0)
{
query = query.Where(c => c.IsKPI == kpidata);
}
result = await query.Include(y => y.TaskActionLogs)
.Include(y => y.AssignedTo)
.Include(y => y.AssignedBy)
.Include(y => y.Project)
.AsSplitQuery()
.ToListAsync();
You can also migrate the if logic to the query too.
&& (!(request.IsKPI == 1 || request.IsKPI == 0) || c.IsKPI == kpidata)
If !(request.IsKPI == 1 || request.IsKPI == 0) returns true, the c.IsKPI == kpidata part will be omitted.
result = await _context.TaskMaster
.Where(c => c.IsActive
&& (c.Status == request.Status || request.Status == "All")
&& (c.ProjectId == request.ProjectId || request.ProjectId == 0)
&& (c.AssignedTo.DepartmentId == request.DepartmentId || request.DepartmentId == 0)
&& (!(request.IsKPI == 1 || request.IsKPI == 0) || c.IsKPI == kpidata))
.Include(y => y.TaskActionLogs)
.Include(y => y.AssignedTo)
.Include(y => y.AssignedBy)
.Include(y => y.Project)
.AsSplitQuery()
.ToListAsync();
This
(request.IsKPI == 1 || request.IsKPI == 0)
can also be revised to:
(new List<int> { 0, 1 }).Contains(request.IsKPI)
Hi I am trying to do this query:
Select ProjInvoiceJour
where NOT (ProjInvoiceJour.ProjInvoiceType == ProjInvoiceType::Onaccount && ProjInvoiceJour.CountryRegionID != "ES")
But I need to do it whit querybuilder:
qbds.addRange(fieldnum(ProjInvoiceJour, ProjInvoiceType)).value(strfmt('!%1',
strfmt("((%1.%2 == %3) && (%4.%5 != '%6'))",
tablestr(ProjInvoiceJour),
fieldstr(ProjInvoiceJour, ProjInvoiceType),
any2int(ProjInvoiceType::OnAccount),
tablestr(ProjInvoiceJour),
fieldstr(ProjInvoiceJour, CountryRegionID),
queryvalue("ES"))));
But the query has some error:
SELECT * FROM ProjInvoiceJour WHERE ((NOT (ProjInvoiceType = 255)))
Thanks
The law of De Morgan comes to rescue:
select ProjInvoiceJour
where !(ProjInvoiceJour.ProjInvoiceType == ProjInvoiceType::Onaccount &&
ProjInvoiceJour.CountryRegionID != 'ES')
is equivalent to:
select ProjInvoiceJour
where ProjInvoiceJour.ProjInvoiceType != ProjInvoiceType::Onaccount ||
ProjInvoiceJour.CountryRegionID == 'ES'
Or in a query:
qbds.addRange(fieldnum(ProjInvoiceJour, ProjInvoiceType)).value(strfmt('((%1.%2 != %3) || (%4.%5 == "%6"))',
tablestr(ProjInvoiceJour),
fieldstr(ProjInvoiceJour, ProjInvoiceType),
0+ProjInvoiceType::OnAccount,
tablestr(ProjInvoiceJour),
fieldstr(ProjInvoiceJour, CountryRegionID),
'ES'));
I have some complex queries like this:
var contents = await db.Contents
.Where(q => q.ContentStatusId == contentStatusId || contentStatusId == 0)
.Where(q => q.ContentTypeId == contentTypeId || contentTypeId == 0)
.Where(q => q.CreatedBy == contentCreatedBy || contentCreatedBy == "0")
.Where(q => q.ModifiedBy == contentModifiedBy || contentModifiedBy == "0")
.Where(q => q.SubjectId == subjectId)
.ToListAsync();
I send the results back to my web API and I do not need any tracking. Does EF automatically add tracking and if so is that an overhead that I do not need. Also if it does then is there a way I can turn off the tracking ?
Yes there is an overhead. You can use AsNoTracking() on IQueryable or your DbSet.
var contents = await db.Contents
.Where(q => q.ContentStatusId == contentStatusId || contentStatusId == 0)
.Where(q => q.ContentTypeId == contentTypeId || contentTypeId == 0)
.Where(q => q.CreatedBy == contentCreatedBy || contentCreatedBy == "0")
.Where(q => q.ModifiedBy == contentModifiedBy || contentModifiedBy == "0")
.Where(q => q.SubjectId == subjectId)
.AsNoTracking()
.ToListAsync();
I have been trying to implement a search page for the admin of my system. Long story short, there a 3 paramaters as criterias. 1. users, 2.projects, 3. customers. The admin can make any combination of those three criterias. for example "I would like to see all users which are assigned to this projects and also all the customers" or "I want to see this customer and this project but all the users" and so on. How do you implement such filtering? I am using asp.net 4.0 and linq just in case.
Here is the function content and it is all. I have made it by if conditions but it is not at all healthy.
public static List<Data.CurrentActivity> GetUsersActivitySearch(string employeeId, string projectId, string customerId, DateTime startDate, DateTime endDate)
{
DataClassesDataContext dc = new DataClassesDataContext(General.ConnectionString);
if(projectId=="" && customerId!="")
return dc.CurrentActivities.Where(t => t.User.RecId.ToString() == employeeId && t.Customer.RecId.ToString() == customerId && t.ActivityDate >= startDate && t.ActivityDate <= endDate).ToList();
else if (projectId != "" && customerId == "")
return dc.CurrentActivities.Where(t => t.User.RecId.ToString() == employeeId && t.Project.RecId.ToString() == projectId && t.ActivityDate >= startDate && t.ActivityDate <= endDate).ToList();
else if (projectId != "" && customerId != "")
return dc.CurrentActivities.Where(t=>t.User.RecId.ToString()==employeeId && t.Customer.RecId.ToString()==customerId && t.Project.RecId.ToString()==projectId && t.ActivityDate>=startDate && t.ActivityDate<=endDate).ToList();
return dc.CurrentActivities.Where(t => t.User.RecId.ToString() == employeeId && t.ActivityDate >= startDate && t.ActivityDate <= endDate).ToList();
}
Now that I see your code, i have a easy solution. You can actually compound where clause on the IQueryable interface because of the lazy execution:
DataClassesDataContext dc = new DataClassesDataContext(General.ConnectionString);
var result = dc.CurrentActivies.Where(t.ActivityDate >= startDate && t.ActivityDate <= endDate);
if(userId.Length > 0)
result = result.Where(t => t.User.RecId.ToString() == employeeId);
if (projectId.Length > 0)
result = result.Where(t => t.Project.RecId.ToString() == projectId);
if (customerId.Length > 0)
result = result.Where(t=>t.Customer.RecId.ToString()==customerId);
return result.ToList();
If you had a generalized object that could represent enough information to display your results. Then you could do something like this:
public IList<SearchResults> Search(string user, string customer, string project)
{
return (from user in context.Users
where SqlMethods.Like(user.Name, user) && user.Length > 0
select new SearchResult
{
... properties you care about
})
.Concat(from project in context.Projects
where SqlMethods.Like(project, project.Name) && project.Length > 0
select new SearchResult
{
///
})
.Concat(from customer in context.Customers
where SqlMethods.Like(customer, customer.Name) && customer.Length > 0
select new SearchResult
{
///
})
.ToList();
}
return (from s in db.StudentMarks
where s.Class == Class && s.Year == Year // this line
orderby s.Year, s.ExamType
select new StudentAddMarks()
{
--Obj
}).ToList();
I am going to return an Object depending on the Class and Year params. I want to remove the where condition when the Class and Year parames are null or zero.
Any ideas please.
Just add a clause handling null or zero values as well:
where ((Class != null && Class != 0) ? s.Class == Class : true) &&
((Year != null && Year != 0) ? s.Year == Year : true)
The above code uses the shorthand if-then-else syntax, that works as follows:
value = (condition ? if_true : if_false);
// ...is equivalent to...
if (condition)
{
value = if_true;
}
else
{
value = if_false;
}
This should work:
where (s.Class == Class && s.Year == Year) || Class == null ||
Class == 0 || Year == null || Year == 0