Reputation: 1289
I have the following Model
Trip Model // think of Grails domain class
public long FerryId { set;get; }
public long FromLocationId { set;get; }
public long ToLocationId { set;get; }
public Ferry Ferry { set;get; }
public Location FromLocation { set;get; }
public Location ToLocation { set;get; }
Then i'm returning a list to the view and looping through trips:
@foreach (var item in Model) {
@item.FerryId //displays fine
@item.Ferry.FerryName //displays fine
@item.FromLocationId //displays fine
@item.FromLocation.LocationName //doesn't work
@item.ToLocationId //displays fine
@item.ToLocation.LocationName //doesn't work
}
The problem is trying to fetch "item.ToLocation.LocationName" and same for "item.FromLocation.LocationName"
I'm confused on why the Ferry.FerryName returns but not the others.
I'm total newpie to C#/MVC3/Razor, but in grails/groovy this would work no prob, any thoughts? and extra general advises? greatly appreciated.
Upvotes: 0
Views: 76
Reputation: 1289
I looked at the documentation and The query wasn't the problem:
var trips = DB.Trips.Include("FromLocation").Include("ToLocation").ToList();
but i had to manualy add the locaiton objects to trip on save:
[HttpPost]
public ActionResult Create(Trip trip)
{
var fromLocation = DB.Locations.Find(trip.FromLocationId);
var toLocation = DB.Locations.Find(trip.ToLocationId);
trip.FromLocation = fromLocation;
trip.ToLocation = toLocation;
if (ModelState.IsValid)
{
DB.Trips.Add(trip);
DB.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View(trip);
}
}
and now i could load nested objects:
@item.ToLocation.LocationName
@item.FromLocation.LocationName
What puzzles me is in the case of the Ferry object i didn't have to add it manually!
Upvotes: 0
Reputation: 29083
What do you mean "doesn't work"? Is there an error message we can diagnose?
Without that, I can just make an educated guess... I am guessing that you are using Entity Framework to retrieve these model objects from a database and that FromLocation and ToLocation are references to another entity. If that's correct, you need to explicitly tell EF to load those properties from the database before passing the model to the view. It's pretty easy... just add .Include("FromLocation").Include("ToLocation")
to your LINQ query for retrieving things from the EF context
See http://msdn.microsoft.com/en-us/library/bb896272.aspx for more info on this 'eager loading' technique and other options you have for loading related entities.
Upvotes: 1
Reputation: 548
It looks right to me which leads me to ask, what is the accessor for FromLocation/ToLocation.LocationName? Is it public?
Sorry, if it is a silly question, but sometimes thats the stuff that gets me...
hth,
\ ^ / i l l
Upvotes: 0