2012-11-12 22 views
1

我有一个类asp.NET MVC输球引用字段的值

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事件探查器和生成查询

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

您需要为CityFrom和CityTo添加Include,或者您可以使这些引用的实体变为虚拟。选项1(包含)避免了选择n + 1问题,因此在ORM之间通信。

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

虚拟解决了这个问题:)因为我对asp.NET真的很陌生,请问您能解释一下选项1的更多细节吗?我不明白这个内容:( –

+0

已更新答案代码示例 –

+0

我非常感谢你的帮助:))并感谢您的更新:) –

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

对此的唯一警告是选择n + 1问题,不包括城市实体。 –