Reputation: 51
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
Upvotes: 4
Views: 10363
Reputation: 23
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]
Upvotes: 0
Reputation: 13399
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);
Upvotes: 7