2010-01-06 30 views
5

我有以下兩個表(基本輪廓):顯示從多個表中的數據在一個視圖作爲列表 - 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來做到這一點,但無法找出步驟。

在此先感謝

回答

3

如果兩個實體之間存在關聯,則可以使用它訪問第二個類型。在這種情況下,您唯一需要做的就是使用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

4

通過在您的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

相關問題