2012-05-05 10 views
5

Tôi đang cố gắng sử dụng LINQ sau để truy vấn sql để có được kết quả. Nhưng nó không hoạt động nếu parentCategoryId trôi qua như vôlàm thế nào để kiểm tra giá trị null trong LINQ để sql

public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId) 
    { 
     var categories = from c in source where c.ParenCategoryId == parentCategoryId select c; 
     return categories; 
    } 

nhưng công trình sau đây nếu null sử dụng trực tiếp vào vị trí của parentCategoryId

public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId) 
    { 
     var categories = from c in source where c.ParenCategoryId == null select c; 
     return categories; 
    } 
+0

if (ParenCategoryID isEqualTo: NULL) sau đó làm những gì bạn muốn. – vishiphone

Trả lời

8

Bạn có thể sử dụng object.Equals, nó sẽ phù hợp trên null giá trị cũng có.

public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId) 
{ 
    var categories = from c in source 
        where object.Equals(c.ParenCategoryId, parentCategoryId) 
        select c; 
    return categories; 
} 
+0

object.Equals sẽ được dịch sang sql? nếu có thì truy vấn sẽ trông như thế nào? – Reniuz

+0

@Reniuz Vâng, nó sẽ là: 'WHERE [t0]. [ParenCategoryId] IS NULL' – Magnus

+0

@Reniuz có, và nó được tối ưu hóa bởi LINQ to Sql tùy thuộc vào giá trị của biến nullable: http: //www.brentlamborn .com/post/LINQ-to-SQL-Null-check-in-Where-Clause.aspx # id_0d234c8d-7ed4-4b1e-97ba-fcc38bb4d277 –

0

Bạn có thể thử như sau séc

public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId) 
{ 
    var categories = from c in source 
        where (parentCategoryId != null? c.ParenCategoryId == parentCategoryId : c.ParenCategoryId == null) 
        select c; 
    return categories; 
}