【问题标题】:asp.NET MVC losing referenced fields' valuesasp.NET MVC 丢失引用字段的值
【发布时间】:2012-11-12 11:16:57
【问题描述】:

我有课

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

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • Virtual 解决了这个问题 :) 由于我对 asp.NET 很陌生,您能否详细解释一下选项 1?我不明白那个包含:(
    • 非常感谢您的帮助 :)) 并感谢您更新 :)
    【解决方案2】:

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

    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; }
    }
    

    【讨论】:

    • 唯一需要注意的是不包括城市实体的选择 n+1 问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    • 2010-11-14
    • 1970-01-01
    相关资源
    最近更新 更多