从viewmodel获取相关数据?

时间:2017-01-09 19:24:14

标签: c# asp.net asp.net-mvc entity-framework

我无法使用Entity Framework获取某些相关数据的值。基本前提是一个“财产”。属于一个单一的社区'和一个'社区'属于单一地区'

我的房产有以下型号:

public class Property
{
    public int ID { get; set; }

    public string Name { get; set; }

    public int CommunityID { get; set; }

    public int PropertyTypeID { get; set; }

    public virtual Community Community { get; set; }

}

和我的社区模型..

public class Community
{
    public int ID { get; set; }

    public string Name { get; set; }

    public Region Region { get; set; }

    public virtual ICollection<Property> Properties { get; set; }
}

并为我的地区......

public class Region
{
    public int ID { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Community> Communities { get; set; }
}

我已经在视图模型中将所有这些结合在了一起......

public class PropertyDetailViewModel
{
    public string Name { get; set; }

    public virtual Community Community { get; set; }

    public virtual Region Region { get; set; }
}

但是,尝试使用以下控制器方法将其推送到视图时会出现问题:

Property property = await db.Property.FindAsync(id);
var viewModel = new PropertyDetailViewModel
{
    Name = property.Name,
    Community = property.Community,
    Region = property.Community.Region
};
return View(viewModel);

在我看来,我正在使用

创建区域名称的占位符
  

@ Html.DisplayFor(model =&gt; model.Region.Name)

但是这显示为空,即使数据库中肯定有有效的条目?

2 个答案:

答案 0 :(得分:0)

您可以使用include,因此您的区域不会为空。

Property property = await db.Property.Include(p => p.Community.Region).FirstOrDefaultAsync(p => p.ID == id);

更详细:Include() in LINQ to Entities query

答案 1 :(得分:0)

尝试在视图模型中展平Region对象,仅使用您需要的字段:

public class PropertyDetailViewModel
{
    public string Name { get; set; }

    public virtual Community Community { get; set; }

    public string RegionName { get; set; }
}

然后更新您的视图模型映射代码:

Property property = await db.Property.FindAsync(id);
var viewModel = new PropertyDetailViewModel
{
    Name = property.Name,
    Community = property.Community,
    RegionName = property.Community.Region.Name
};
return View(viewModel);

最后更新视图以在视图模型中使用展平的RegionName属性:

@Html.DisplayFor(model => model.RegionName)

在查询语句中与.Include()结合使用以提高性能