显示从多个表中的数据在一个视图作为列表 - ASP.Net MVC

显示从多个表中的数据在一个视图作为列表 - ASP.Net MVC

问题描述:

我有以下两个表(基本轮廓):显示从多个表中的数据在一个视图作为列表 - ASP.Net MVC

Tbl_CategoryType

ID LevelID 说明

Tbl_Levels ID 名称

基本上,我想在引用Tbl_Levels.Name数据时在Tbl_CategoryType表中提供所有信息基于Tbl_CategoryType.LevelID号码。

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

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}); 
} 

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

我假设我需要通过自定义viewmodel来做到这一点,但无法找出步骤。

在此先感谢

如果两个实体之间存在关联,则可以使用它访问第二个类型。在这种情况下,您唯一需要做的就是使用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

+1

谢谢,这工作。 – shif 2010-01-06 09:16:34

通过在您的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. 
    } 

让您查看继承来自MyViewModel。

+0

这是行不通的。您必须创建匿名类型,然后将数据复制到MyViewModel集合。 – LukLed 2010-01-06 07:52:40

+0

哦,看起来他的方法想要一个IQueryable。感谢您的光临。 – womp 2010-01-06 07:54:35

+0

对不起,我忘了提及我正在使用实体框架。 – shif 2010-01-06 09:18:58