How do I use 'OR' operator to return all rows if string is empty in linq to sql - linq-to-sql

I've a linq query :
var Employees = db.EmployeeMasterAs
.Where(x => x.SystemCode == SysCode && x.EmployeeCode == EmpCode)
.ToList();
the above query works fine if all values in the where clause are provided. If EmpCode is supplied a value, it returns the corresponding data, which works fine. However, I've no idea about how to return all rows if EmpCode is not supplied.
If I were to use SQL, I would have done it this way :
SELECT * FROM EmployeeMasterAs
WHERE SystemCode == #SysCode AND (EmployeeCode == #EmpCode or '')
I've no idea how to translate the above query into linq syntax. Any Help will be deeply appreciated, Thanks in Advance :)

you can even write something like this
...&& (EmpCode == null || x.EmployeeCode == EmpCode) )
which i find simplier than #Dr Ivol

Related

Multiple conditions in linq lambda query

Three conditions in linq where clause using lambda expressions
List<Tbl_MVPConsultant> _objConsultants = _datalayer.Get_MVP_Consultants();
_objConsultants = _objConsultants.Where(p => p.Country.ToLower().Contains(SearchTextbox.ToLower()) ||
p.State.ToLower().Contains(SearchTextbox.ToLower()) ||
p.City.ToLower().Contains(SearchTextbox.ToLower())).ToList();
I'm trying to achieve a filter operation three times using the above query .. but i'm getting an error stating object reference not set to an instance of an object ..
Looking for a quick solution.Appreciate early efforts.
Thank you
You won't be able to call p.Country.ToLower if p.Country is null. Put p.Country != null && p.State != null && p.City != null && at the start of the lambda.

SELECT ... INTO Understanding its behavior

I was told that I could check whether a SELECT statement finds a column with the syntax
$rows = query( "SELECT * FROM tbl WHERE id = idx");
if ( $rows == false )
and it seems to work.
Anyway, if I check if ( $rows == 0 ) it doesn't return the same value.
Shouldn't 0 and false be the same (apart from the type, of course)?
What's the actual value returned by the query when it finds no row? I ask because it doesn't seems to be false, since the statement var_dump( $rows === false ) prints false..
***EDIT: I'm sorry guys, query() was a function from a library someone else wrote and I had no idea (i'm starting now with sql...). It simply excutes an SQL statement, returning an array of all rows in result set or false on (non-fatal) error (like row not found).
I have still a little question, though.
The function returns false when it finds no row, so shouldn't I be able to catch that with if ( $rows === false )?
Why var_dump(false) doens't print me out anything, while var_dump(true) prints me out 1?
I'm not pretty sure if you use simple mysql_* functions, MySQLi or PDO but in any case $rows is not returning the number of resulting rows. It is a boolean value / object returned / created depending of success of your query.
$sql = $mysqli->query("SELECT * FROM tbl WHERE id='1'");
if(!$sql->error)
$number_of_rows = $sql->num_rows; // for sure it will output 1

NHibernate.ISession.Linq<T>.Where(expression) retrieves whole table

I am using NHIbernate against MySql, and when I use the following statement, NHibernate Profiler shows me that the query passed to MySql is basically SELECT * FROM tablename with NO WHERE clause. The LINQ expression isn't applied until after all the data are retrieved. This is obviously not acceptable from a performance standpoint. What am I doing wrong?
Session.Linq<T>().Where(expression).AsQueryable()
Thanks!
[UPDATE]
As #GertArnold guessed, the call preceding this was:
public IQueryable<Student> FindByExpression(Func<Student, bool> expression)
The expression was:
_studentRepository.FindByExpression(t =>
(t.Teacher.Id == dto.TeacherId) &&
(t.Id != dto.Id) &&
(
(t.ExternalId != null && student.ExternalId != null
)
You should use an Expression<Func<T, bool>> instead of Func<T, bool>.

LINQ to SQL generates negative conditions in WHERE clause

I am using LINQ to SQL to retrieve data, using boolean conditions (BIT columns in SQL). My LINQ query looks something like this:
var query = from r in db.Requests
select r;
query = query.Where(r => r.Completed == someBooleanVal);
query = query.Where(r => r.Cancelled == someOtherBool);
return query.ToList();
The 'Where()' gets applied in a different method, that's why I'm putting it in separately.
When the boolean values are given as false, the generated SQL looks something like this:
SELECT [t0].[col1], [t0].[col2], [t0].[col3], [t0].[etc]
FROM [dbo].[Requests] AS [t0]
WHERE (NOT(([t0].[Cancelled]) = 1) AND (NOT(([t0].[Completed]) = 1)
in stead of what I would use:
WHERE [t0].[Cancelled] = 0 AND [t0].[Completed] = 0
This runs very, very slowly. I strongly suspect that it is because of the negative conditions on the boolean values it generated (all the selected columns are covered by an index, and the two columns in the where clause have a separate index on them).
Why is it generating negative conditions? How can I fix it?
var query =
from r in db.Requests.Where(r => r.Completed == someBooleanVal && r.Cancelled == someOtherBool)
select r;
return query.ToList();
Hope it can help you and have a nice day.

Simple math question with LinQ, simple Join query, Nulls, etc

I have 2 tables
1. Client
2. Operations
Operations can result in: Credits or Debits ('C' or 'D' in a char field) along with date and ammount fields.
I must calculate the balance for each client's account using linQ... The result should also show balance 0 for clients whom didn't make operations yet
I have the following function with linQ statement, but I know it could be done in a better and quicker, shorter way, right? Which will be?
public static double getBalance(ref ClasesDeDatosDataContext xDC, string SSN,
int xidClient)
{
var cDebits =
from ops in xDC.Operations
where (ops.idClient == xidClient) && (ops.OperationCode == 'D')
select ops.Ammount;
var cCredits =
from ops in xDC.Operations
where (ops.idClient == xidClient) && (ops.OperationCode == 'C')
select ops.Ammount;
return (double)(cCredits.Sum() - cDebits.Sum());
}
Thanks !!!
I don't know if the LINQ-to-SQL engine can handle the expression, but something like this should be possible:
return (
from ops in xDC.Operations
where ops.idClient == xidClient
select ops.operationCode == 'C' ? ops.Amount : -ops.Amount
).Sum(a => a);
Or perhaps:
return (
from ops in xDC.Operations
where ops.idClient == xidClient
select new { Sign = ops.operationCode == 'C' ? 1.0 : -1.0, Amount = ops.Amount }
).Sum(o => o.Sign * o.Amount);
If the collection is empty, the Sum method returns zero, so that takes care of clients without transactions.
Edit:
Corrected spelling in query: Ampont -> Amount