【问题标题】:Displaying data from multiple tables in a view as a list - ASP.Net MVC将视图中多个表中的数据显示为列表 - ASP.Net MVC
【发布时间】:2010-01-06 07:36:13
【问题描述】:

我有以下两张表(基本大纲):

Tbl_CategoryType

身份证 等级ID 说明

Tbl_Levels ID 名称

基本上,我想在基于 Tbl_CategoryType.LevelID 编号引用 Tbl_Levels.Name 数据时呈现 Tbl_CategoryType 表中的所有信息。

我已尝试在我的存储库中使用如下连接;

public IQueryable GetAllTypesInCategory(int CatID)
{
     return (from x in DBEntities.LU_LST_CategoryTypeSet
             where x.CategoryID == CatID && x.Enabled == 1
             join y in DBEntities.LU_LST_LevelSet on x.LevelID equals y.ID
             select new {x, y});
}

但是,当我调用该方法时,没有可以分配给它的类型,因为它不适合 Category 或 Level 的类型。

我假设我需要通过自定义视图模型执行此操作,但无法弄清楚步骤。

提前致谢

【问题讨论】:

    标签: asp.net-mvc linq-to-entities viewmodel


    【解决方案1】:

    通过在您的 linq 语句中使用这一行:

    select new {x, y}
    

    您正在创建一个新的匿名类型,它与您的实体类型不同。

    我猜您没有使用 EntityFramework 或其他会自动解析外键关系以创建链接实体的重型框架。如果为真,那么是的,您需要创建一个 ViewModel。

    只需创建一个简单的包装类,其中包含每个实体之一作为属性。

    public class MyViewModel
    {
        public MyViewModel(LU_LST_CategoryTypeSet x, LU_LST_LevelSet y)
        {
            Category = x;
            Level = y;
        }
    
        public LU_LST_CategoryTypeSet Category { get; set;}
        public LU_LST_LevelSet Level { get; set; }
    }
    

    然后在您的 Linq 语句中,创建 MyViewModel 类型,而不是创建匿名类型:

    public IQueryable GetAllTypesInCategory(int CatID)
    {
         return (from x in DBEntities.LU_LST_CategoryTypeSet
                 where x.CategoryID == CatID && x.Enabled == 1
                 join y in DBEntities.LU_LST_LevelSet on x.LevelID equals y.ID
                 select new {x, y});
    }
    

    然后将结果复制到您的模型类中:

       var listOfTypes = GetAllTypesInCategory(catID);
       foreach (var item in listOfTypes)
       {
          var model = new MyViewModel(item.x, item.y);
    
          //Do whatever with the model to get it to the view.
       }
    

    让你的 View 继承自 MyViewModel。

    【讨论】:

    • 这行不通。您必须创建匿名类型,然后将数据复制到 MyViewModel 集合。
    • 哦,是的,看起来他的方法需要一个 IQueryable。感谢现场。
    • 很抱歉,我忘记提及我使用的是实体框架。
    【解决方案2】:

    如果两个实体之间存在关联,您可以使用它访问第二种类型。在这种情况下,您唯一需要做的就是使用 Include() 方法来加载关联数据。

           public List<LU_LST_CategoryType> GetAllTypesInCategory(int CatID)  
             { 
                 return (from x in DBEntities.LU_LST_CategoryTypeSet.Include("LU_LST_LevelSet") 
                         where x.CategoryID == CatID && x.Enabled == 1  
                         select x).ToList(); 
             }
    

    比每个LU_LST_CategoryTypeSet category 都可以打电话给category.LU_LST_Level

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多