简体   繁体   中英

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

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?

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

如果你想返回一个特定数据类型的特定值,比如 int,就像在我的例子中我想返回一个 int,将 IQueryable 转换为一个数组,然后使用 ArrayName[0] 进行转换

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM