2012-10-22 27 views
1

我是新來的C#和我有困難的時候搞清楚了這一點,在C#編寫服務器存儲過程

public UserNotificationFeed GetNotificationFeed(TenantInfo tenant, List<int> notificationId) 
{ 
    UserNotificationFeed userNotificationFeed = new UserNotificationFeed(); 

    string sql = "select " + NotificationFieldList + " from UserNotificationFeed where MsgId = @MsgId"; 

    Database databaseObj = SocialDB.GetDataBase(tenant.ConnectionString, tenant.ProviderName); 
    DbCommand commandObj = databaseObj.GetSqlStringCommand(sql); 

    databaseObj.AddInParameter(commandObj, "MsgId", DbType.Int64, notificationId); 

    using (IDataReader reader = databaseObj.ExecuteReader(commandObj)) 
    { 
     while (reader.Read()) 
     { 
      userNotificationFeed = new UserNotificationFeed(); 
      this.PopulateObject(userNotificationFeed, reader); 
     } 
    } 

    return userNotificationFeed; 
} 

我想的是,

string sql = "select " + NotificationFieldList + " from UserNotificationFeed where MsgId = @MsgId"; 

採取MsgId列表s傳遞了一個List<int> notificationId

任何幫助真的很感激。

+1

這不是一個「存儲過程」,順便說一句 - 它只是一個命令。不重要的一點 - 只是一些術語。 –

+0

你是否收到異常?是不是運行 –

+1

隨機問題:如果有多個id,你的代碼目前只返回**最後一行**。你打算在這種情況下做什麼? –

回答

0

一個簡單的方法,因爲數據是int(因此注射安全)將只使用:

string sql = "select " + NotificationFieldList + 
    " from UserNotificationFeed where MsgId in (" + 
    string.Join(",", notificationId) + ")"; 

(不加參數)如果你想讓它

完全參數化,這也是可能的,但更難(它需要靈活的參數數量)。不過,有些工具可以提供幫助。例如,dapper這將是:

var rows = connection.Query("select " + NotificationFieldList + 
    " from UserNotificationFeed where MsgId in @MsgId", 
    new {MsgId = notificationId}).ToList(); 

這裏短小精悍會自動調整的SQL,並添加參數的正確數目。但是:短小精靈不會直接與你的IDataReader-PopulateObject方法(因爲它已經已經填充一些對象)。