【问题标题】:How to pass two LINQ joined tables from Controller to View如何将两个 LINQ 连接表从控制器传递到视图
【发布时间】:2013-12-12 19:55:41
【问题描述】:

我有三个对象:

public class Part
{
    [Key]
    public int ID { get; set; }
    public string Number { get; set; }
    public string Name { get; set; }
    public int descID { get; set; }    
}

public class Description
{
    [Key]
    public int descID { get; set; }
    public string descName { get; set; }
    public string description { get; set; }
}

public class GridPart
{
    public string name{ get; set; }
    public string number { get; set; }
    public string description { get; set; }            
}

我正在使用LINQ 在 descID 列上加入 Part 和 Description:

public ActionResult Index()
{    
    var myParts = from p in db.Parts
                  join d in db.Description on p.descID equals d.DescriptorID
                  select new { Description = d.description, Name = p.name};
    List<GridPart> partsList = new List<GridPart>();

    foreach (var m in myParts)
    {
        GridPart gp = new GridPart();
        gp.Name = m.name;
        gp.description = m.description;                    
        partsList.Add(gp);
    }
    return View(partsList);
}

如果我只是使用 Parts 表,在视图中我会这样做:

@model IEnumerable<MyApp.Models.Part>

如果我正在使用连接表,我该怎么办?这同时使用了 Parts 和 Description,更不用说我的 GridParts 列表,我如何通过它来显示我需要的所有数据?

非常感谢任何建议。

【问题讨论】:

    标签: asp.net-mvc linq entity-framework


    【解决方案1】:

    如果您将匿名类型传递给您的视图,它将不会被强类型化。你可以像这样引用你的模型

    @Html.TextBox("Name")
    

    @Html.Display("Name")
    

    虽然这可行,但我建议不要这样做 - 更好的解决方案是使用 Viewmodel 代替。这将使您的视图具有强类型。

    编辑:再次查看此内容,我发现您实际上并未将匿名类型解析为您的视图。您正在解析 GridParts 列表。

    您应该能够像您尝试过的那样强烈键入您的视图 - 只需引用 GridParts 而不是部件。

    @model IEnumerable<MyApp.Models.GridPart>
    

    【讨论】:

    • 您可以使用 AutoMapper 将您的 IQueryable 复制到 ViewModel 中
    • 感谢您的反馈。我真的是 ASP.net MVC 的新手,在我的情况下我将如何使用 ViewModel?
    • 感谢您的 Morten Anderson。我在 VS 中遇到了构建错误,经过清理和重建后,一切正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2013-05-23
    • 2014-09-26
    相关资源
    最近更新 更多