Adapting from this C# MVC tutorial I'm using the following statement to return a specific user to the view
User user = db.Users.Find(id);
if (user == null){return HttpNotFound();}
return View(user);
The Users
model has a foreign key to Auctions
so the view can iterate over a list of auctions associated with this user.
Auctions
has a field called buyerID
which corresponds with User.ID
so I want to display the buyers name by linking back to User.userName
by way of the Auctions.buyerID
.
I can do this in SQL statements and LINQ as well but I think there is a simpler way.
How can I use, User user = db.Users.Find(id);
and join it to User
from the foreign key of Auctions.buyerID
?
This is kind of what I thought would work but I can't create a new parameter 'buyerName' when User doesn't have this.
IEnumerable<User> thisUser = from usr in db.Users
join auct in db.Auctions on usr.ID equals auct.UserID
join ur in db.Users on auct.buyerID equals ur.ID
where usr.ID == id
select new User
{
buyerName = ur.userName
};
From other posts like this one I read about setting up a new class but that doesn't seem to stick to the DRY & KISS principles since now I need to have two classes that vary by one parameter located in different locations.
Is there a simpler way to join the table and get the strong typing without creating a new class?
So the result should display the buyers name instead of the buyers ID#