1

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#


enter image description here

1 Answer 1

0

Since I wanted to avoid using anonymous type and I didn't want to create a new class I found a work around by passing a dictionary of user names to the view.

Controller

User user = db.Users.Find(id);

var dict = db.Users.Select(t => new { t.ID, t.userName })
           .ToDictionary(t => t.ID, t => t.userName);

ViewData["userDict"] = dict;

Now I just looked up the username based on the buyer ID

View

@{Dictionary<int, String> userList = ViewData["userDict"] as Dictionary<int, String>;}

@{
  if (item.buyerID.HasValue)
  {
    @Html.DisplayFor(modelItem => userList[item.buyerID.Value])
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.