1

我是 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由 a 传递的 s列表List<int> notificationId

非常感谢任何帮助。

4

1 回答 1

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();

在这里,dapper 将自动调整 SQL 并添加正确数量的参数。但是:dapper 不能直接使用IDataReader基于- 的PopulateObject方法(因为它已经填充了一些对象)。

于 2012-10-22T10:35:39.197 回答