Linq to SQL null values in GridView - linq-to-sql

Normally if I'm linking an ObjectDataSource to a GridView and I have a TemplateColumn that has an Eval in it and it's Null, I can just put a ".ToString()" it works fine. For some reason, this doesn't work the same when you're using Linq to SQL.
I originally was using XSD files for my DAL with a custom BLL. I tied it to the GridView with an ObjectDataSource. I'm in the middle of swapping out the XSD files with Linq to SQL and everything is working just like the old way except for the columns that can have Null values.
Has anyone run into this before and if so, how do I work around this problem?

Most everything that LINQ returns is of Nullable types. So in your binding expressions you need to use GetValueOrDefault().ToString() or the new "??" null coalescing operator rather than just plain old ToString(). I hope this helps. Check this link out to.
Example:
// this will output the int if not null otherwise an empty string.
<%# (int?)Eval("MyIntegerField") ?? "" %>

Related

Creating an OR statement using existing conditions hash

I am working on a problem where I need to add an OR clause to a set of existing conditions. The current conditions are built in a hash in a method and at the end, they are used in the where clause. Here is a simplified example:
...
conds.merge!({:users => {:archived => false}})
Model.where(conds)
I am trying to add an OR clause to the current set of conditions so it would be something like '(conditions) OR new_condition'. I'd like to add the OR statement without converting each addition to the conds hash into a string. That would be my last option. I was hoping someone has done something like this before (without using Arel). I seem to recall in Rails 2 there was a way to parse a conditions hash using a method from the model (something like Model.some_method(conds) would produce the where clause string. Maybe that would be a good option to just add the OR clause on to that string. Any ideas are appreciated. Thank you for your help!
I found a way to do what I needed. Instead of changing all of the conditions that I am building, I am parsing the conditions to SQL using sanitize_sql_for_conditions. This is a private method in ActiveRecord, so I had to put a method on the model to allow me to access it. Here is my model method:
def self.convert_conditions_hash_to_sql(conditions)
self.sanitize_sql_for_conditions(conditions)
end
So, once I convert my conditions to text, I can add my OR clause (along with the appropriate parentheses) to the end of the original conditions. So, it would go something like this:
Model.where('(?) OR (model.type = ? AND model.id IN(?))', Model.convert_conditions_hash_to_sql(conds), model_type, model_id_array)

Dynamic Linq failing when using Contains against Int Field

I'm using Entity Frameworks 4.1.0.0 and MySQL.Data.Entity 6.5.4.0 and when I try and generate a dynamic query for a range of integers, I get an error of:
No applicable method 'Contains' exists in type 'Int32'
This seems to work fine when using a similar structure to check against Strings..but I want to expand this to support the other db fields I have in my data.
Code Example:
int[] ids = new int[] { 1, 3, 4 };
IQueryable<entityname> list = db.tablename.Where("Id.Contains(#0)", ids);
I have added in the Dynamic.cs to my project and followed along with
http://blog.walteralmeida.com/2010/05/advanced-linq-dynamic-linq-library-add-support-for-contains-extension-.html
but there has been no difference then using the Dynamic I loaded via Nuget.
Thank you in advance.
The syntax is slightly different:
IQueryable<entityname> list = db.tablename.Where("#0.Contains(outerIt.Id)", ids);
following the link you refer to.
If you need to check if a given (variable) int value is contained within a entity column, you can do the following using Dynamic Linq:
return query.Where(String.Format("{0}.ToString().Contains(#0)", field), value);
Check out this answer for an extension method that can perform such task with strings, integers and booleans column types in a rather seamless way.

Problem with fieldname having '?'

I have a 'user' table with a field name 'process_salary?' which has a boolean datatype
#user = User.create(params[:user])
if #user.process_salary?
//some code here
else
//some code here
end
When I create a new object of user and check for process_salary it gives me following error
NoMethodError: undefined method `process_salary?' for #<User:0xb6ac2f68>
Why does this error occur? Can I avoid it without changing my column name?
When I check it with the debugger it crashes the first time, but after that it runs properly
The question-mark has a special meaning in ActiveRecord. It can be used to check whether a field is true. You are using it as part of your field name which wasn't such a good idea. You could try if #user.process_salary?? exists but I think ultimately it is easiest to change your database column to be called 'process_salary'.
Side note: The 'rails console' is really helpful for playing around with models.
As cellcortex posted, question marks at the end of column names are tricky in Rails. If you need to have it there for legacy reasons, you might be able access the attribute as follows:
#user['process_salary?']
or the more verbose:
#user.read_attribute['process_salary?']
You can of course test for nil using .nil?.

ISingleResult Cast in Code?

I have a sproc in my Linq to SQL (.NET 4.0) designer that returns the default ISingleResult. I wanted it to return something of Type "MyTable", so I made the change in the designer.
So this works:
List<MyTable> return = dataContext.MySproc.ToList();
However, I would rather cast/convert the return from the sproc in code to stay away from the designer. For some reason I can't get the trick of converting ISingleResult from the sproc into List. Can someone help me with the syntax?
Note, if this is easier in EF and someone can point me to HOWTOs using that toolset, I'm all ears.
Thanks.
Just pass your ISingleResult into the constructor of List.

MS Access default value

I have a text column in one of my MS Access tables that is empty be default when a new record is inserted. The problem I have is that I can't seem to check whether this field is empty with EITHER equals Null or equals "" . For example, neither of these "reads" the field as being empty:
If [Field] = "" Or [Field] = Null Then
I've always used Access 2007 to develop this database, and I recently opened it with Access 2003, which is when I think this problem started. Could that be the cause? If so, would simply opening and saving it again with Access 2007 solve it?
When you compare against null, you need to use the IsNull function. With traditional ANSI SQL logic, Null <> Null, so you need a special function to test for null.
If [Field] = "" Or IsNull([Field])
First off, I would suggest that you do one of two things:
set your fields to disallow zero-length strings. That way you'd have to test only Is Null.
if you feel you must allow storage of ZLS, then set the default value to a ZLS. It's still possible for the field to end up Null, though, so this may or may not be helpful.
I don't see storage of ZLS's as having any utility whatsoever. It's almost always a shortcut to accomodate data being appended from sources that return ZLS's instead of Nulls for empty fields.
You should also read up on Nulls. Allen Browne has a number of pages that explain it all quite well:
Nulls: Do I need them?
Common Errors with Null
Aspects of working with Nulls in VBA code:
Nothing? Empty? Missing? Null?
The articles are Access-oriented, but could be valuable to those using any database, particularly relative novices because of the conversational style of the writing.
You should try:
If Nz([Field], "") = "" Then
Because:
If [Field] = ""
in:
If [Field] = "" Or IsNull([Field])
Would still throw a Null Error!