I am trying to pass a null to DataAdapter.Fill. My SQL statement accepts nulls but I get a return that nulls are not acceptable.
JUEGO.etreDataSetTableAdapters.CountyTableAdapter etreDataSetCountyTableAdapter = new JUEGO.etreDataSetTableAdapters.CountyTableAdapter();
etreDataSetCountyTableAdapter.Fill(etreDataSet.County, null);
CollectionViewSource CViewSource = ((CollectionViewSource)(this.FindResource("CViewSource")));
CViewSource.View.MoveCurrentToFirst();
the CountryTableAdapter has the SQL Statement below behind it.
SELECT DISTINCT CCODE FROM HH_Match WHERE (#DCODE IS NULL OR DCODE = #DCODE)
but when I pass Null like above it returns a massage that nulls are not allowed. I am working in Visual Studio (C#) 2012. Thanks in advance for the help
You have to configure the TableAdapter manually so that it accepts null.
Therefore click on Parameters in the query property. Select the parameter you want to make optionally (in this case you have only one parameter). On the right side you'll find AllowDbNull. Set this to True and you've arrived.
Related
Is it possible to generate a raw SQL statement for insert/update operations using nHibernate without actually executing them? Assuming of course that everything (mappings, connectionStrings, etc.) is properly configured?
The closest thing I've found is to call:
Session.SessionFactory.GetClassMetadata(typeof(Client))
Which returns an object of type SingleTableEntityPersister containing SQLIdentityInsertString, that looks like this:
INSERT INTO Client (FirstName, LastName) values (?, ?)
But it would still require me to bind all of the properties manually, and on top of that SQLIdentityInsertString is a protected property. Are there any proper ways of doing that?
Okay, the closest thing I've found is to construct your own sql query with a string builder. First you need to extract your class metadata:
var metaData = Session.SessionFactory.GetClassMetadata(typeof(Client)) as SingleTableEntityPersister;
Then you can retrieve other information, such as:
var propertyNames = metaData.PropertyNames;
var tableName = metaData.TableName;
var firstPropertyValue = metaData.GetPropertyValue(client, propertyNames[0], EntityMode.Poco);
Once you have that information you can construct your own query manually. Not exactly the solution I wanted, but it's as close as it gets, I think.
However, one thing to note is that Session.CreateSQLQuery(string) method is currently bugged, and as a result SetParameter method doesn't work with more than 10 named parameters. There already seems to be a bug report created for this on NHbiernate's Jira.
I just realized that when I request this
Orders.Where(y => y.Sub_Item_Id.Substring(0, 10) != y.Sub_Item_Site_Id.Substring(0, 10))
The query ignore all my null value that may exist in y.Sub_Item_Site_Id. So when I have a value in Sub_Item_Id and null in Sub_Item_Site_Id the query does NOT consider this as !=.
Why?
I also tested the same query with SQL
select
*
from
orders as o
where
LEFT(o.sub_item_id, 10) <> LEFT(o.sub_item_site_id, 10)
And I get the same result. I have all my different value but NOT when I have a value in o.sub_item_id and null in o.sub_item_site_id.
Could you explain how and why SQL and Linq is working like this.
Substring() doesn't ignore null, in your query if one of the strings will be null you will get NullPointerException and if one of the string is shorter than 10 symbols, you will get ArgumentOutOfRangeException:
https://msdn.microsoft.com/library/aka44szs(v=vs.110).aspx
Check your data nad your query.
You may want to add a tag indicating that your LinQ in the background connects to a database to execute SQL there. Without that information, Maksim is correct. In plain Linq-to-Objects C# you would get the appropriate exceptions.
However, as your LinQ is translated and executed as SQL, you just met a surprisingly unintuitive SQL feature: NULL is never equal to anything else. Not even NULL. And NULL is never not equal to anything else. No even a value or another NULL. It just never yields true in a comparison, whatever you compare it to.
You can use the IS syntax to ask if something is NULL. Or you can replace your NULL with a default value before doing your statement. But comparing existing values and NULL will always yield false because NULL is not equal to anything, not even NULL itself.
Relational expressions involving NULL actually yield NULL again. In order to filter null values, you need to use the IS NULL and IS NOT NULL. You can find an answer here.
I trying to do the following query using dapper but its always returning a empty result set. First I tried to remove the WHERE clause in order to isolate the problem but that didn't work. After that I added a alias to the C.NAME column in the SELECT clause but didn't work either.
private const string SelectClaims =
#"SELECT C.NAME FROM CLAIMS C
INNER JOIN USERS_CLAIMS UC ON C.ID = UC.ID_CLAIM
WHERE UC.ID_USER = #Id";
using (var conn = new FbConnection(connectionString))
{
var claims = conn.Query<string>(SelectClaims, new { user.Id });
return claims;
}
If I replace the query above for this right here everything works fine:
SELECT NAME FROM CLAIMS
To be honest I am not sure if you are using Dapper properly since you are selecting named column and mapping it to simple string - I believe Dapper doesn't see 'Name' property as fails silently. I guess you should try either Query<T> with strongly typed object or use Query<dynamic> to avoid unnecessary class creation.
So, I put this aside and go do something else and after I came back to try to solve my problem everything was working fine. I didn't change anything in my code and surprisingly its working right now.
I don't know if is possible that a pending transaction in my MiTeC Interbase Query was blocking me to see the current records from the database. I try to simulate this again and now its always returning the records that I need (better that than nothing, hehe).
For clarification, its perfect fine to use a string as the returning data type, do a simple join in sql parameter to a Query method or don't use a alias for the returning column at all (only if all columns matches your C# property names or you just have a column directing to a string like me).
Here's a scenario that I am working on : Right now we have a SQL statement that reads like this :
SELECT a.ID,a.MsgNumber,CASE WHEN #HasAccess=1 THEN Title ELSE '*********' END AS Title FROM Messages
We want that operators be able to see if a message registered in system but can't see the title if they are not authorized.
I'm changing this part of code so we can use a NHibernate criteria to generate the same result (so we can produce dynamic queries according to filters that user selects).
I know that I can use projections to get some fields or constant values from a criteria but can not figure out how I should combine them to do what I want.
It looks like #HasAccess is a parameter passed in by your code, not a value determined by the database. If so, then the easiest way to do what you want is to modify the criteria in code based on the value that you would pass through in the query, eg:
var projections = Projections.ProjectionList()
.Add(Projections.Id())
.Add(Projections.Property("MsgNumber"))
.Add(hasAccess ? Projections.Property("Title") : Projections.Constant("*********"));
var criteria = session.CreateCriteria<Message>()
.Add(... your restrictions ...)
.SetProjection(projections)
.List<object[]>();
If however #HasAccess is determined by your database somehow, then you could use:
Projections.Conditional(Restrictions.Eq("HasAccess", 1),
Projections.Property("Title"),
Projections.Constant("*********"))
assuming that you can get HasAccess into your criteria somehow
I have a linq to sql query where I have to perform union two set of records.
And I do not have equal number of fields, so added the null
eg my psuedo code is
var Values=( from c in containers
some joins
select new PValues
{
regionid=r.regionid,
roomid=r.roomid,
floorid=r.floorid,
maxarea=r1.maxarea,
minarea=r1.minarea,
avgarea=r1.avgarea,
maxheight=r1.maxheight,
minheight=r1.minheight
})
.union
( from c in containers
some joins
select new PValues
{ regionid=j.regionid,
roomid=j.roomid,
floorid=j.floorid,
maxarea=null,
minarea=null,
avgarea=null,
maxheight=j1.maxheight,
minheight=j1.minheight
})
after googling some hours I came to understand that it is bug in 3.5 framework.
Now I want to retrieve the result.
How do I do that
I tried framing into two seperate iqueryable
var a= first query
var b =second query
ilist result =a.union b
This too results in the same error.
How should I form it
Thanks in advance
Regards
Hema
This is most likely the result of a known issue with LINQ to SQL. When a column value is referenced twice, it gets optimized out of the result set (even though you may need it to make unions line up).
The most general-purpose work-around is to use let statements:
var Values=(
from c in containers
some joins
//You'll need one let statement for each COLUMN, even if they share a value.
let maxAreaValue = null
let minAreaValue = null
let avgAreaValue = null
select new PValues
{
regionid=j.regionid,
roomid=j.roomid,
floorid=j.floorid,
maxarea=maxAreaValue,
minarea=minAreaValue,
avgarea=avgAreaValue,
maxheight=j1.maxheight,
minheight=j1.minheight
});
More information:
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=355734
http://slodge.blogspot.com/2009/01/linq-to-sql-and-union-all-queries.html
SqlException about UNION, INTERSECT and EXCEPT
In SQL, this typically means that you need to cast those nulls as the appropriate data type of the first part of the union, so make them the default values for the types you need, like "" or String.Empty for string values, or 0 for ints, etc...
Cast the nulls as mentioned by #GalacticJello, but also cast the first query's parameters that will have nulls in the other query to a nullable version of the type. For instance, if minarea is decimal, cast it to a decimal?; you can do this via: new Nullable(i.minarea) to ensure it infers the correct type.
It's probably inferring a different anonymous signature for both queries. Also, to mitigate the problems, make a class with these properties and change the query from:
select new { .. }
to
select new MyObj { .. }
And that will resolve it too.