LINQ to SQL defining Where class depending on parameters - asp.net

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

Related

Expressions in a querybuildRange

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

Cant filter dynamic query

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

return record through LINQ statement

DataContext db = new DataContext();
Select_Utilities SelectedUtility = (from su in db.Select_Utilities
where su.id == SelectUtilityId
&& su.Worksite_Id == WorksiteId
&& su.Utility_Company.id == UtilityCompanyId
select su).FirstOrDefault();
then I wanted to say SelectedUtility.comment = "whatever the comment may be";
BUT getting ERROR: cannot implicity convert type 'Select_Utility' to 'Select_Utilities'
with 'FirstOrDefault' in statement....any advice?
Thanks
Change result type to Select_Utility
Select_Utility SelectedUtility = // here
(from su in db.Select_Utilities
where su.id == SelectUtilityId &&
su.Worksite_Id == WorksiteId &&
su.Utility_Company.id == UtilityCompanyId
select su).FirstOrDefault();
I'm guessing Select_Utilities is the name of your Entity table which ruturns a collection of Select_Utility objects. Try:
Select_Utility selectedUtility = (from su in db.Select_Utilities
where su.id == SelectUtilityId
&& su.Worksite_Id == WorksiteId
&& su.Utility_Company.id == UtilityCompanyId
select su).FirstOrDefault();

How to write a JDO query to check multiple object attributes with one string parameter?

My Owner class has 6 string attributes. I want to write a JDO query which should check a string with those all 6 attributes of Owner class and if any of those 6 attribute matches then that owner object should be added in list. I am using following JDO query syntax but its not working:
String branchName = req.getParameter("branch");
List<Owner> owners = null;
Query query = pm.newQuery(Owner.class);
query.setFilter("branch1 == branchParam || branch2 == branchParam || branch3 == branchParam || branch4 == branchParam || branch5 == branchParam || branch6 == branchParam");
query.declareParameters("String branchParam");
companies = (List<Owner>) query.execute(branchName);
i am getting following exceptoin:
org.datanucleus.store.appengine.query.DatastoreQuery$UnsupportedDatastoreFeatureException: Problem with query <SELECT FROM com.eplinovo.stallbokenapp.domain.HastForetag WHERE branch1 == branchParam || branch2 == branchParam || branch3 == branchParam || branch4 == branchParam || branch5 == branchParam || branch6 == branchParam PARAMETERS String branchParam>: Or filters cannot be applied to multiple properties (found both branch1 and branch2).
Any idea how can i write a query for that. Thanks in advance.

How to implement filtering search for admin

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

Resources