I have a class
public partial class Advertisement
{
public int AdvertisementId { get; set; }
public string Description { get; set; }
public City CityIdFrom { get; set; }
public City CityIdTo { get; set; }
public int Weight { get; set; }
}
which represents the table Advertisements. Same goes for a class City
public class City
{
public Int32 CityId { get; set; }
public string Name { get; set; }
}
Now I have a view controller named View1Controller which has
DbConnection db = new DbConnection();
public ActionResult Index()
{
var query = from item in db.Advertisements.AsEnumerable() select item;
return View(query);
}
And finally there is a View1.cshtml file
@model IEnumerable<MvcApplication1.Models.Advertisement>
@{
ViewBag.Title = "View1";
}
<h2>View1</h2>
<table>
@foreach(var item in Model)
{
<tr>
<td>@item.Description</td>
<td>@item.CityIdFrom</td>
</tr>
}
</table>
I took a look in SQL Profiler and the query generated looked
SELECT
[Extent1].[AdvertisementId] AS [AdvertisementId],
[Extent1].[Description] AS [Description],
[Extent1].[Weight] AS [Weight],
[Extent1].[CityIdFrom_CityId] AS [CityIdFrom_CityId],
[Extent1].[CityIdTo_CityId] AS [CityIdTo_CityId]
FROM [dbo].[Advertisements] AS [Extent1]
And executing the query I get:
2 None 5000 1 2
3 Test 1000 3 4
However, when query is hit, both CityIdFrom and CityIdTo are null for some reason. Thus the result table looks
None
Test
Instead of expected
None 1
Test 3
What am I doing wrong?
you either need to add an Include for CityFrom and CityTo, or you Can make these referenced entities virtual. Option 1 (Include) avoids the select n+1 issue so commomn among ORMs.