2015-11-23 48 views
1

我想使用Dapper.SimpleCRUD檢索層次結構中的根節點。根節點由沒有父節點標識。這就是我正在做的電話:Dapper.SimpleCRUD - ISNULL

var whereConditions = new object { ParentId = (int?)null, CompanyId = 1 }; 
var root = db.GetList<T>(whereConditions).FirstOrDefault(); 

這是生成的SQL:

exec sp_executesql N'Select * from [Folders] where [CompanyId] = @CompanyId and [ParentId] = @ParentId',N'@CompanyId int,@ParentId int',@CompanyId=13,@ParentId=NULL 

的問題是,[ParentId] = @ParentId將返回任何記錄爲@ParentId爲空。爲了匹配記錄,該聲明將需要爲[ParentId] IS NULL

我不知道是否SimpleCRUD可以檢測何時可空參數等於NULL並且可以生成IS NULL語句?這樣的事情:

exec sp_executesql N'Select * from [Folders] where [CompanyId] = @CompanyId and [ParentId] IS NULL',N'@CompanyId int,@ParentId int',@CompanyId=13,@ParentId=NULL 

我知道我可以手動發送WHERE字符串,但希望有一個自動SimpleCRUD方法。

如果我錯過了一些明顯的東西並感謝您的時間,請提前道歉。在GitHub上

回答

0

艾瑪·德 - 格魯特好心指出問題here

你好約翰,我居然還碰到了這個問題,今天也是如此。問題 似乎來自「BuildWhere」,其中有一個硬編碼的「=」等號。

private static void BuildWhere(StringBuilder sb, 
IEnumerable<PropertyInfo> idProps, object sourceEntity) { .... } 

我創造了這個解決辦法來解決我的問題:

private static void BuildWhere(StringBuilder sb, IEnumerable<PropertyInfo> idProps, object sourceEntity, object whereConditions = null) 
var propertyInfos = idProps.ToArray(); 
string param = ""; 

... 

try 
{ 
    // use the 'is null' operator if value of parameter null, else use '=' operator 
    param = (whereConditions.GetType().GetProperty(propertyToUse.Name).GetValue(whereConditions, null) != null ? "{0} = @{1}" : "{0} is null"); 
} 
catch (Exception err) 
{ 
    param = "{0} = @{1}"; 
}     

sb.AppendFormat(param, GetColumnName(propertyToUse), propertyInfos.ElementAt(i).Name); 
0

我看着這個一點點接近,真的不喜歡實施的東西,必須是在嘗試的想法/趕上工作。

你可以在這種情況下使用手動方法嗎?

var user = connection.GetList("where age = 10 or Name like '%Smith%'"); 

或在您的情況:

var user = connection.GetList("where ParentId is null AND CompanyId = 1"); 

你可以很容易地生成一個不同的地方根據,如果是的ParentId空子句。