mvc4 How to extract value from a tolist query in controller

大城市里の小女人 提交于 2019-12-25 16:03:28

问题


Ok so this is the basic setup; A user logins I get the unique ID of that user myid, I then try to get a list of that logged in user friends by going into the friends table which is shown in the variable myfriends notice that I have only selected the friendID column which represents the uniqueID of a friend. I then compare the myid to the profileID which should match if they're friends. The problem is that I am using a .tolist() on the myfriends variable and I can't seem to extract the friendID (I am using the tolist() because a user can have more than 1 friend but the tolist only counts the amount of records) to compare in the friendprofile variable because the .tolist() only gives a value of how many records are extracted. How can I get the friendID value from myfriends so that I can compare it in the friendprofile so that I can show the users friends profile ? any help would be great

       [Authorize]
        public ActionResult myprofile()
    {
// Logged in User unique ID                     
int myid = Convert.ToInt32(User.Identity.Name);
 // list of Logged in User friends by ID
                    var myfriends = sqlConnection.Query<friend>("Select friendID from friends where myid=@profileID",new { profileID = myid }).ToList();
                    // get friends profiles
                    var friendprofile = sqlConnection.Query<profile>("Select * from profiles where friendID=@profile",new { profile = myfriends }).ToList();
   }

回答1:


You can do this is a single query using the SQL IN Operator

int myid = Convert.ToInt32(User.Identity.Name);
var friendprofile = sqlConnection.Query<profile>("Select * from profiles where friendID IN (Select friendID from friends where myid=@profile)",new { profile = myid }).ToList();


来源:https://stackoverflow.com/questions/26458486/mvc4-how-to-extract-value-from-a-tolist-query-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!