简体   繁体   中英

C# Check null in LINQ query and Transaction Scope giving underlying connection failed to open

I have been messing with 2 problems for quite some time and i have tried alot of things but still i am getting the problems. Following is the simplified version of the first problem.

I have a LINQ query in which p.XP and XP is of type double? . When the value of XP is "null" the query return wrong results even though i have a null in the p.XP field in the database.

from p in entity.positions
where p.XP == XP
select p;

I also tried different things suggested by other threads on SO like

from p in entity.positions
where Object.Equals(p.XP , XP)
select p;

This gives me following exception

Unable to cast type System.Nullable to System.Object.

How to resolve this issue ?

Problem 2: For LINQ i am using TransactionScope to handle transactions. When i execute the queries i get an exception

Underlying connection failed to Open.

and the inner exception is saying something about DTC. I read online that i will have to enable some service on the server. But i donot want to do that. How can i use transcactions without enabling DTC. My code is something like this

public void function1()
{
     using(TransactionScope t = new TransactionScope())
     {
         RunSomeSelectQueries();
         RunSomeInsertQueries();
         RunSomeUpdate Queries();

         t.Complete();
     }
}

In your first problem, you need to check for nulls separately from the comparisons, because nulls are treated separately.

   var foo = (from p in entity.positions
                where (p.XP == null && XP == null)
                  || (p.XP == XP)
              select p);

These are really two problems and should be separated into two questions.

But I do have an answer for the first one. In SQL database NULL is not equal to NULL. This is because NULL is meant to represent and unknown value and it is not possible to declare that an unknown is equal to another unknown.

To clarify:

"SELECT * FROM sometable where 1 = 1" would return all rows, because "1 = 1" is TRUE

"SELECT * FROM sometable where 1 = 0" would return no rows, because "1 = 0" is FALSE

"SELECT * FROM sometable where NULL = NULL" or "SELECT * FROM sometable where 1 = NULL" would return no rows, because "NULL = NULL" or "1 = NULL" is equal to a new "boolean" state called NULL. A query will only return a row if the WHERE clause is TRUE.

To extract the row where XP is NULL, you must expand your where clause to something like this:

from p in entity.positions
where p.XP == XP || (p.XP == null && XP == null)
select p;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM