1

我有一堂课

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

我究竟做错了什么?

4

2 回答 2

2

你要么需要为 CityFrom 和 CityTo 添加一个 Include,要么你可以使这些引用的实体成为虚拟的。选项 1(包含)避免了在 ORM 中常见的 select n+1 问题。

var query = db.Advertisements.Include("CityIdFrom").Include("CityIdTo").AsEnumerable();
return View(query);
于 2012-11-12T02:32:41.223 回答
1

如果您使用的是实体框架,则需要将属性设为虚拟。

public partial class Advertisement
{
    public int AdvertisementId { get; set; }
    public string Description { get; set; }
    public virtual City CityIdFrom { get; set; }
    public virtual City CityIdTo { get; set; }
    public int Weight { get; set; }
}
于 2012-11-12T02:48:46.227 回答