asp.NET MVC丢失了引用字段的值

时间:2012-11-12 02:27:33

标签: asp.net entity-framework-4 asp.net-mvc-4 foreign-keys

我有一个班级

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

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您需要为CityFrom和City To添加Include,或者您可以将这些引用的实体添加为虚拟。选项1(包括)避免了在ORM中如此常见的选择n + 1问题。

var query = db.Advertisements.Include("CityIdFrom").Include("CityIdTo").AsEnumerable();
return View(query);

答案 1 :(得分: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; }
}