How to find one value from an IQueryable in C# ASP.NET MVC 4 using Linq

asp.net asp.net-mvc c# entity-framework linq

Question

Hi guys this is in C# ASP.NET MVC 4 using EF. I have a table Users which has Portfolio object defined as one of its properties and Username as another. The User.Identity.Name in Razor lets me pass the username along to my controller once the person is logged in. A User has a Portfolio_Id in the table from the Portfolio object. What I am trying to do is obtain the Portfolio_Id of a User when all I have to go buy is the Username. In the code below you see I have a var protfolioId. My problem is that it is getting set as an IQueryable<int> from my LINQ when I need it to just be and int. I may be wrong but does that mean it is a collection and not a single value? How can I get just the Portfolio_Id for the User whose Username matched what I passed into the action? Any help would be appreciated. Thank you.

public ActionResult Index([Bind(Prefix="id")]string userName)
    {
        //find the user
        var user = _db.Users
                   .Where(u => u.UserName == userName)
                   .Select(u => new User
                   {
                       Id = u.Id,
                       UserName = u.UserName,
                       FirstName = u.FirstName,
                       LastName = u.LastName,
                       Email = u.Email,
                       Portfolio = u.Portfolio
                   });
        //find the users portfolio id
        var portfolioId = user.Select(u => u.Portfolio.Id);

        //find their portfolio
        var portfolio = _db.Portfolios.Find(portfolioId);
        if(portfolio == null)
        {
            return HttpNotFound();
        }//end of if
        return View(portfolio);
    }//end of Index
1
4
11/24/2013 4:20:25 PM

Accepted Answer

var portfolio = _db.Users
                   .Where(u => u.UserName == userName)
                   .Select(u =>u.Portfolio)
                   .FirstOrDefault();
if(portfolio == null)
        {
            return HttpNotFound();
        }//end of if
        return View(portfolio);
6
11/24/2013 4:23:46 PM

Popular Answer

If you want to return a particular value in a specific data type like say int, like in my case i wanted to return an int, convert the IQueryable to an array then convert using ArrayName[0]



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow