views:

212

answers:

2

I'm learning ASP.NET MVC (and MVC in general) and all the help online I find only demonstrates using a single table, not relations between multiple tables. I'm running a query that I expect should also return associated entities, but it's not and can't figure out what I'm missing. I appreciate your help!

I have the following data:

Ticket
   TicketID  CompanyID  Subject  ...
   --------  ---------  -------
   1         1          "stuff"
   2         1          "things"

Company
   CompanyID  Name      ...
   ---------  --------
   1          "FredCo"

So every ticket is linked to a specific company. I am trying to create a Details view for Tickets, and I want to display the company name. Here is what I have set up at the moment.

Model

A Ticket entity and a Company entity, and there is an association called CompanyTicket between them. The navigational properties are Ticket.Company and Company.Tickets.

In the mapping details for the association, I have:

Maps to Ticket
    Company.CompanyID <-> CompanyID
    Ticket.TicketID   <-> TicketID

Controller

My TicketController.Details method looks like this:

public ActionResult Details( int id )
{
    var tickettoview = ( from m in _db.Ticket
                         where m.TicketID == id
                         select m ).First();
    return View( tickettoview );
}

Edit: After going through Mark Hamilton's suggestion, I realize the problem is my query. Putting a breakpoint on the return shows that tickettoview never has Customer populated. So this narrows it down, but I'm still not sure how to populate the Company attribute.

Again, thank you!

+1  A: 

This sounds like the same problem I had when I asked this question. See the answer I posted that described how I fixed it.

I was using Linq to SQL rather than Linq to Entities, but I'm assuming the DataLoadOptions and LoadWith method (or something like it) still works. Someone more knowledgable about the Entity Framework can correct me if I'm wrong.

Matt Hamilton
I can't figure out how to use DataLoadOptions, but I now realize that the problem is all in my controller, the query isn't running a sub-query. I'll edit my question.
Stephen Jennings
Ahh! "Linq to entities" was the vocabulary I needed to find the answer in Google. Thanks.
Stephen Jennings
+2  A: 

Matt's answer gave me the vocabulary I needed for this, and eventually brought me around to this page. Adding .Include("Company") to my data set populated the Company property.

var tickettoview = ( from t in _db.Ticket.Include("Company")
                     where t.TicketID == id
                     select t ).First();
Stephen Jennings