我有一堂课
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; }
}
代表表格广告。一流的城市也是如此
public class City
{
public Int32 CityId { get; set; }
public string Name { get; set; }
}
现在我有一个名为 View1Controller 的视图控制器,它有
DbConnection db = new DbConnection();
public ActionResult Index()
{
var query = from item in db.Advertisements.AsEnumerable() select item;
return View(query);
}
最后还有一个 View1.cshtml 文件
@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>
我查看了 SQL Profiler,生成的查询看起来
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]
并执行我得到的查询:
2 None 5000 1 2
3 Test 1000 3 4
但是,当查询被命中时,CityIdFrom 和 CityIdTo 出于某种原因都为空。因此结果表看起来
None
Test
而不是预期
None 1
Test 3
我究竟做错了什么?