MVC LINQ to SQL Table Join Record Display

前端 未结 3 1777
攒了一身酷
攒了一身酷 2020-12-16 09:08

Im having problems displaying records to my view when passing viewdata to a user control. This is only apparent for linq to sql objects where I am using table joins.

相关标签:
3条回答
  • 2020-12-16 09:21
    foreach (table1 m in (IEnumerable)ViewData.Model)
    

    m is not of type table1. It is an anonymous type (select new { ... } in CViewDataUC.cs).

    You should create a class that represents the type of the model objects you are passing from controller to view.

    0 讨论(0)
  • 2020-12-16 09:27

    Thanks, this has helped me a lot!

    One small comment, you have to use angle brackets:

    IQueryable<CInformation> info = from table1 in dataContext.table1
    
    0 讨论(0)
  • 2020-12-16 09:36

    Thanks, that worked like a charm. I totally overlooked the problem, I guess it's a Monday that's why :P. But for the people that run in the same problem and are still new to MVC and LINQ to SQL the problem is solved easily do these steps:

    1. Create a class CInformation.cs Add variables similiar to your query

      public class CInformation {

      public CInformation() { }
      
      public string _column1{ get; set; }
      public string _column2{ get; set; }
      ...
      

      }

    2. In your query

      public void uc_VDGenInfoDC(ViewDataDictionary viewData, int id) {

          var dataContext = new testDataContext();
      
          IQueryable<CInformation> info = from table1 in dataContext.table1
                                          join table2 in dataContext.table2 on table1.type_id equals table2.type_id        
                                          join table3 in dataContext.table3 on table1.id equals table3.id                  
                                          join table4 in dataContext.table4 on table1.id equals table4.id                       
                     where table1.test_id == id
                     select new CInformation
                     {
                         _column1 = table1.column1.ToString(),
                         _column2 = table2.column1.ToString(),
                         ...
                     };         
      
          viewData["vd_Info"] = info;
      
      }
      
    3. In your User Control or view

      foreach (CInformation m in (IEnumerable)ViewData.Model){

       m.column1
       m.column2
       ...
      

      }

    0 讨论(0)
提交回复
热议问题