2010-11-25 46 views
0

比方說,我有這兩個表:的WinForms和實體框架:在的WinForms父數據網格視圖顯示子實體數據

類別

Id int primary key, 
Name nvarchar(50) not null, 
Description ntext null, 
AnotherColumn nvarchar(20) not null, 
AndYetAnotherColumn nchar(10) null 

產品

Id int primary key, 
CategoryId int not null (references Category.Id), 
Name nvarchar(20) not null 
OtherStuff... 

我有一個Product實體,它具有導航EntityReference類型Category,即一個產品可以只屬於一個類別,但一個類別可以具有多個產品。

比方說,我想要在網格中顯示產品,但我還想在產品數據網格中顯示Category.NameCategory.AndYetAnotherColumn以及產品信息。

如果我簡單地綁定DataGridView控制到Products實體對象,它顯示顯示Category類的System.Type命名Category結合所述Category導航屬性的列,並且每行該列中的單元,這恰好爲MyProjectNamespace.Category

如何在不創建和綁定另一個ViewModel或Repository或一些自定義類的情況下將我需要的混合數據返回給數據網格?這是一個項目要求,我不創建一個ViewModel或一箇中產階級。

+0

你需要一箇中產階級denormalise數據;數據網格將在網格上的單行中顯示單行數據。按照Devart的解決方案,使用匿名類型可能是最簡單的選擇。 – 2010-12-27 11:31:22

回答

2

使用如下代碼:

Entities db = new Entities(); 
var q = from it in db.Products 
     select new 
     { 
      it.Id, 
      it.Name, 
      it.OtherStuff, 
      it.Category.Name, 
      it.Category. AndYetAnotherColumn 
     }; 
dataGridViewInstance.DataSource = q.ToList(); 
0

另一種解決方案是在數據庫中創建一個視圖,使用的EntityFramework來映射爲一個新的實體