Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more: , +
hi experts

1. a sql server 2008 table that contains many columns and some of them are checked "not null"
like this:
SQL
create table Book(
    ID bigint identity(1,1) not null,
    Name nvarchar 50 null,
    ISBN nvarchar 10 not null,
    ......


2. in c#4, visual studio 2010, i use linq to sql. like:
C#
var context = new Model().Books;
var query = from b in context 
    select b;



the question is , how can i get only "allowed null" columns? i want linq to sql realize if the field is "allow null" or not?
Posted
Updated 25-May-12 6:38am
v2

This might help: http://weblogs.asp.net/grantbarrington/archive/2009/03/17/using-reflection-to-determine-whether-an-type-is-nullable-and-get-the-underlying-type.aspx[^]

There is some information on getting Nullable on msdn (http://msdn.microsoft.com/en-us/library/ms366789.aspx[^]), but only for types. You cannot use the object.GetType() to determine if something is Nullable because if you do a GetType() on an int? you just get the result of int. This code will work with typeof() (ie typeof(int?)):

C#
public static class Extensions
{
    public static bool IsNullable(this Type type)
    {
        return type.IsGenericType
                     && (type.GetGenericTypeDefinition() == typeof(Nullable<>));
    }
}


This code will work with generics;

XML
public class x<T>
{
    public x()
    {
        var x = typeof(T).IsNullable();
    }
}
 
Share this answer
 
Comments
Vartan Khachatourian 26-May-12 0:12am    
thank you but i didn't mean int? , i mean nullable for nvarchar. you know we don't have string? type . please give me solution exactly for my example (Book table)
Clifford Nelson 26-May-12 0:23am    
I was thinking of the classes created and completely missed the issue with NVARCHAR. Obviously there is no way to simulate as a type NVARCHAR since string is nullable.
Hi,

please read this topic from stackoverflow, I think it's what you want to achieve.

http://stackoverflow.com/questions/413084/equivalent-of-sql-isnull-in-linq[^]

Regards
 
Share this answer
 
Comments
Clifford Nelson 25-May-12 18:53pm    
He is looking to figure out if fields can have a null value, not if they are null.
Vartan Khachatourian 26-May-12 0:14am    
im looking to realize if field can have a null value not if it is null

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900