This is not about DBNull vs Null. I understand the difference.
What I would like to know is if I am using Linq, say to access a User.EmailAddress, then checking User.EmailAddress == null is the same as User.EmailAddress == DBNull correct?
My reasoning is that the absence of data in the database results into Linq not generating an object reference, which then means that null is in fact equivalent to DBNull when used with Linq.
Is my reasoning correct or not?
You shouldn't use DBNull with LinqToSql. The point is Language Integration, and so one concept or name for null will suffice.
Here's the select statement that works in LINQ to SQL for Visual Basic. I assume it will be the same in C#.
User.EmailAdress.Equals(Nothing)
For example:
Dim EmptyEmailAddressEntries = From User in DC.Users _
Where User.EmailAddress.Equals(Nothing) select User
Will give you all the Users that have nothing in the email address. To check for entries with space " " characters only add
Or
User.EmailAddress = ""
In LINQ to SQL, you should be using null rather than DBNull. LINQ to SQL is an OR mapper, so it works with objects in a native way. The whole goal with L2S is to allow you to work with objects in a standard .NET way, and let L2S handle all the mapping between native and DB specific for you. You should avoid using DBNull in any L2S statements...in fact, I'm not even sure that is even a valid check (it'll probably cause some odd behavior if it works at all.)
Related
I need do a filtering query with some query parameter. I need that if the query parameter is null, the condition of the query (= or LIKE, for example) is not evaluated and return me everything. I'm using R2DBC and I don't find a way to solve it.
If you are using Spring Data R2dbc, besides the above raw SQL query, you can use R2dbcOperations to compose Criteria by condition freely.
The following is an example.
template
.select(Post.class)
.matching(
Query
.query(where("title").like("%" + name + "%"))// extract where here you can assemble the query condition freely.
.limit(10)
.offset(0)
)
.all();
Additionally using R2dbcRepository and convention-based method, try to use a default value in the like(eg. set the null to empty string "" in like) to save work to determine if it is a null value in sql.
A general prepared statement which would work might be:
SELECT *
FROM yourTable
WHERE col = ? or ? IS NULL;
In the event that you bind a NULL value to the ? from your obfuscation layer, the WHERE clause would always be true, returning all records in the table.
If you prefer doing this with a "static SQL statement" (meaning you use a single SQL string for all possible bind values), then, in Oracle, it's probably optimal to use NVL() to profit from an Oracle optimiser feature, as explained in this article, irrespective of whether you're using R2DBC:
SELECT *
FROM t
WHERE col = nvl(:bind, col)
However, a query like yours is often best implemented using dynamic SQL, such as supported by a third party library like jOOQ:
Flux<TRecord> result =
Flux.from(ctx
.selectFrom(T)
.where(bind == null ? noCondition() : T.COL.eq(bind))
);
You can obviously also do this yourself, directly with R2DBC and your own dynamic SQL library, or any other such library.
Disclaimer: I work for the company behind jOOQ.
I have the following LINQ query; I want to remove dot character if available at the end of string
var hatoList = (from L in db.vHatoList select L.HatoFullName.Trim('.')).ToList();
You're currently trying to perform the query in the database. We don't know what database technology you're using, so it's hard to know whether there's some way to make it actually happen in the database, but it's probably simplest to do in memory instead (given that it won't change how many records will be returned). The AsEnumerable() method is used to just change the compile-time type to IEnumerable<T> (instead of IQueryable<T>) forcing the rest of the query to be evaluated in .NET code instead of in the database:
var hatoList = db.vHatoList
.AsEnumerable()
.Select(entry => entry.HatoFullName.TrimEnd('.'))
.ToList();
(I've also changed the call from Trim to TrimEnd to avoid it removing periods at the start of the string.)
You are using linq to sql and database does not understand TrimEnd or Trim.
So first you have need to load data in memory and then use TrimEnd method.
var hatoList = (from L in db.vHatoList select L.HatoFullName).ToList().
Select(t=>t.TrimEnd('.'));
I tried DapperExtensions, Dapper.Extensions.Linq and linq2dapper to no avail. I will try Dapper.SimpleCRUD-with-Oracle. I will probably settle with a Stored Procedure instead. I want to use TableDirect with no embedded SQL statement. How can I use Dapper and Linq with a TableDirect? Or, how can I use TableDirect without embedded SQL, and filter a table?
Following are my problems:
I could not create Predicate without run time error.
I need missing configuration
I got ORA error about table saying "column not correct, runtime error".
How to use Dapper LINQ with TableDirect (without embedded SQL) with ORACLE?
You can achieve this with simple Dapper. For example, look at the following code from Dapper:
public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?));
Look at the last commandType parameter. It supports the TableDirect value that you are looking for.
As far as other extensions of Dapper you mentioned in question, I do not think they will support it. I know for sure Dapper Extensions do not support it; not sure about others.
This is because, those extensions are basic query generators written over Dapper. So, you are using them for generating the query and in that case, that parameter value will/should be Text. If you want to use other values, bypass the extension and use simple Dapper.
If you want to simply provide a table name or stored procedure name, why use query generator? Just use Dapper.
I used //https://github.com/jmo21/Dapper.SimpleCRUD-with-Oracle-/blob/master/Dapper.SimpleCRUD/SimpleCRUD.cs . No nuget package for this ORACLE dialect. It just obfuscates the WHERE clause, and it is an answer, when I the organization probably will not like SELECT.. FROM ... WHERE...
We don't have SQL injection possible in any case.
Is there a way to do
"UPDATE Item SET start_date = CURRENT_TIMESTAMP" ?
in Nhibernate without using hql/sql.
I am trying to avoid hql/sql because the rest of my code is in criteria. I want to do something like :
var item = session.get<Item>(id)
item.start_date = current_timestamp
There are two ways and sql is correct one.
Either you will
load all entities, change, update and commit, or
write sql query and let dbms handle most of the work
I am trying to avoid hql/sql because the rest of my code is in criteria
That is not a valid argument. Criteria is an API intended for relational search, and it does not support mass updates.
Different tasks, different APIs.
In this case, you can use either HQL or SQL, as the syntax is the same. I recommend the former, because you'll be using your entity/property names instead of table/column ones.
So I'm extremely new to Linq in .Net 3.5 and have a question. I use to use a custom class that would handle the following results from a store procedure:
Set 1: ID Name Age
Set 2: ID Address City
Set 3: ID Product Price
With my custom class, I would have received back from the database a single DataSet with 3 DataTables inside of it with columns based on what was returned from the DB.
My question is how to I achive this with LINQ? I'm going to need to hit the database 1 time and return multiple sets with different types of data in it.
Also, how would I use LINQ to return a dynamic amount of sets depending on the parameters (could get 1 set back, could get N amount back)?
I've looked at this article, but didn't find anything explaining multiple sets (just a single set that could be dynamic or a single scalar value and a single set).
Any articles/comments will help.
Thanks
I believe this is what you're looking for
Linq to SQL Stored Procedures with Multiple Results - IMultipleResults
I'm not very familiar with LINQ myself but here is MSDN's site on LINQ Samples that might be able to help you out.
EDIT: I apologize, I somehow missed the title where you mentioned you wanted help using LINQ with Stored Procedures, my below answer does not address that at all and unfortunately I haven't had the need to use sprocs with LINQ so I'm unsure if my below answer will help.
LINQ to SQL is able hydrate multiple sets of data into a object graph while hitting the database once. However, I don't think LINQ is going to achieve what you ultimately want -- which as far as I can tell is a completely dynamic set of data that is defined outside of the query itself. Perhaps I am misunderstanding the question, maybe it would help if you provide some sample code that your existing application is using?
Here is a quick example of how I could hydrate a anonymous type with a single database call, maybe it will help:
var query = from p in db.Products
select new
{
Product = p,
NumberOfOrders = p.Orders.Count(),
LastOrderDate = p.Orders.OrderByDescending().Take(1).Select(o => o.OrderDate),
Orders = p.Orders
};