【问题标题】:Fill list from joined table LINQ从联接表 LINQ 中填充列表
【发布时间】:2020-05-29 17:05:17
【问题描述】:
using System.Collections.Generic;  
using ViewModelsDemo.Models;  

namespace ViewModelsDemo.ViewModels  
{  
    public class CustomerViewModel  
    {  

        public List<JoinedTableClass> JoinedTable { get; set; }  
    }  
    public class JoinedTableClass
{

    public string FirstField { get; set; }  // Table1
    public string SecondField { get; set; } // Table2
    public string ThirdField{ get; set; }  // Table 2


}

}  

我尝试执行以下操作,但没有成功。

        var customerViewModel = new CustomerViewModel  
        {

            JoinedTable = (from Cust in Tables.Customer

            join D in Tables.Dep on Cust.Customer_ID equals D.ID

            select new CustomerViewModel  { Cust.FirstName , Cust.LastName , D.Serialz })

        };

        return View(customerViewModel);

在最后一行,我有以下错误:

无法使用已初始化的集合启动类型“CustomerViewModel”,因为它没有实现 System.Collections.Ienumerable

【问题讨论】:

    标签: c# asp.net-mvc linq


    【解决方案1】:

    //改变你的实现 如果你只想要 JoinedTableClass 的列表,那么使用这个

                var JoinedTable = (from Cust in Tables.Customer
                      join D in Tables.Dep on Cust.Customer_ID equals D.ID
                     select new JoinedTableClass
                     {
                       FirstField = Cust.FirstName ,
                       SecondField = Cust.LastName ,
                       ThirdField = D.Serialz 
                     }).ToList()
    
    
    
            return View(JoinedTable );
    

    【讨论】:

    • 我之前确实尝试过,但这并没有帮助。每当我编译System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[WebApplication2.JoinedTableClass]'时我都会得到这个,但是这个字典需要一个'WebApplication2.CustomerViewModel'类型的模型项。从搜索中,我相信它与@model WebApplication2.CustomerViewModel有关我的视图的顶部......但我仍然无法弄清楚它是什么。
    • @model IEnumerable
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    相关资源
    最近更新 更多