显示从多个表中的数据在一个视图作为列表 - 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
答
通过在您的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。
谢谢,这工作。 – shif 2010-01-06 09:16:34