【问题标题】:mvc4 take value from a tolist query and apply it to another querymvc4 从 tolist 查询中获取值并将其应用于另一个查询
【发布时间】:2014-10-21 06:29:34
【问题描述】:

我的控制器中基本上有 (2) 个 .Tolist() 查询;我想做的是从特定列中获取数字列表并将其嵌入到控制器中的第二个 .tolist 查询中,这个例子应该清除它

int myid = Convert.ToInt32(User.Identity.Name);
// I would like to get extract the info. from ProfileID column and use in comments tolist
var friendprofile = sqlConnection.Query<profile>("Select * from  profiles where ProfileID In (Select ProfileID from followings where me=@profile)", new { profile = myid }).ToList();
var comments = sqlConnection.Query<comment>("Select * from comments where profileID=@profile", new { profile = friendprofile}).ToList();

var friendprofile 每次运行时都会起作用;它给了我正确的 2 个配置文件的计数(该用户只有 2 个朋友)现在我想获取 ProfileID (从 me=@profile 的以下内容中选择 ProfileID) 的 int 值并使用这些cmets 变量 中的值。 friendprofile 变量获取用户的好友资料列表,并提取他或她的好友唯一 ID(ProfileID);和评论变量选择用户朋友 cmets 。我知道这部分是错误的 profile =friendprofile;我本来想做这样的事情 profile =friendprofile.followings.ProfileID 但我不能,因为它是一个列表,任何帮助或建议都会很棒。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 dapper


    【解决方案1】:

    试试这个,

    将您的第二个选择查询修改为,

            string profileIdValues = string.Empty;
            foreach (string proId in profileIds)
            {
                profileIdValues = proId + ", " + profileIdValues;
            }
            // Will remove the trailing ',' from the profileIdValues.
            profileIdValues = profileIdValues.Remove(profileIdValues.Length - 2, 1);
            var comments = sqlConnection.Query<comment>("Select * from comments where profileID IN (@profile)", new { profile = profileIdValues }).ToList();
    

    注意:在此处相应地更改您的个人资料 ID 类型,我假设为字符串。

    【讨论】:

    • 前 5 行代码可以简化为 var profileIdValues = String.Join(",", friendprofile.Select(f =&gt; f.ProfileID));,但无论如何您都不能将其传递给 SQL IN 子句 - 它需要是 ... where IN (1, 3, 5) 假设它的 int... where IN ('1', '3', '5') 如果它的varchar
    • @StephenMuecke 谢谢,我不会保留它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 2014-04-06
    相关资源
    最近更新 更多