0

在 HomeController.cs 我有以下片段

   public ActionResult Index()
    {
        var context = new DataClassesContext();
        var regionBoudaries = from boundaryDetails in context.RegionBoundaries
                              join boundaryID in context.Region_Boundaries on boundaryDetails.RegionBoundaryID equals boundaryID.BoundaryID
                              select new { boundaryDetails.lat, boundaryDetails.@long, boundaryID.RegionID };
        ViewData["RegionBoudaries"] = regionBoudaries;
        return View();
    }

在我写的视图文件中

 <%= ViewData["RegionBoudaries"] %>

我将整个 LINQ 查询翻译成 SQL 语言,而不是查询的结果。你能帮我得到查询的结果吗?谢谢

4

1 回答 1

3

当然你需要执行查询:

 ViewData["RegionBoudaries"] = regionBoudaries.ToList();

但据我所知,您正在使用一个匿名对象,这将使其难以在视图中访问。所以我建议你定义一个模型:

public class RegionViewModel
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public int RegionID { get; set; }
}

然后调整您的查询:

var context = new DataClassesContext();
var regionBoudaries = 
    from boundaryDetails in context.RegionBoundaries
    join boundaryID in context.Region_Boundaries on boundaryDetails.RegionBoundaryID equals boundaryID.BoundaryID
    select new RegionViewModel
    {
        Latitude = boundaryDetails.lat, 
        Longitude = boundaryDetails.@long, 
        RegionID = boundaryID.RegionID 
    };

改进代码的下一步当然是摆脱这种ViewData废话并充分利用您定义的视图模型和视图中的强类型:

public ActionResult Index()
{
    using (var context = new DataClassesContext())
    {
        var regionBoudaries = 
            from boundaryDetails in context.RegionBoundaries
            join boundaryID in context.Region_Boundaries on boundaryDetails.RegionBoundaryID equals boundaryID.BoundaryID
            select new RegionViewModel
            {
                Latitude = boundaryDetails.lat, 
                Longitude = boundaryDetails.@long, 
                RegionID = boundaryID.RegionID 
            };
        return View(regionBoudaries.ToList());
    }
}

现在您的视图将成为视图模型的强类型:

<%@ Page 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewPage<IEnumerable<RegionViewModel>>" 
%>

现在你得到了强类型和智能感知:

<% foreach (var region in Model) { %>
    <div>
        Lat: <%: region.Latitude %>, Lon: <%: region.Longitude %>
    </div>
<% } %>
于 2013-02-17T17:21:14.463 回答