How to pass query results with FK (EF) relations to a view
I cannot figure out this simple thing in ASP.NET MVC:
I have two tables:
Customer:
CustomerID
FirstName
LastName
AddressID
AddressTemporaryID
Address:
AddressID
Street
City
I have my relationship (FK) set in DB and trying to use Entity Framework. My navigation properties (FK) are called Addresses and Addresses1. I created a repository:
public interface ICustomertRepository {
IQueryable<Customer> FindAllCustomers();
}
public class CustomerRepository : MvcApplication2.Models.ICustomerRepository {
public IQueryable<Customer> FindAllCustomers() {
return db.Customers;
}
}
And my HomeController has this:
public ActionResult Index()
{
var query = customerRepository.FindAllCustomers();
return View(query);
}
But how can I access the values ββin my view? I can see item.Adresses.Street / item.Adresses1.Street with Intellisense in the model, but when I try, I get a NullReferenceException:
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%= Html.Encode(item.FirstName) %>
</td>
<td>
<%= Html.Encode(item.Surname) %>
</td>
<td>
<%= Html.Encode(item.Adresses.Street) %>
</td>
<td>
<%= Html.Encode(item.Adresses1.Street) %>
</td>
</tr>
<% } %>
I am completely lost. I tried to search everywhere but without success.
source to share
EF does not perform automatic lazy loading.
You either need to manually load related objects (not executable for many results, like your query), or instruct EF to include the desired properties for the whole query:
public IQueryable<Customer> FindAllCustomers() {
return db.Customers.Include("Adresses").Include("Adresses1");
}
You can find a comparison of how to do this between EF and LinqtoSQL (if you're used to it) in this post . At least it will show you the EF syntax.
source to share
In fact, in your scenario, where AddressId
and Address1Id
are the FK in the table below:
Until the actual links (address and address1) are loaded, unless you do Include()
or explicitAddressReference.Load().
Actual FK value is loaded into Entity in EntityReference EntityKey ie
addressID = item.AddressReference.EntityKey.EntityKeyValues[0].Value;
Hope this helps Alex
source to share