2013-05-17 17 views
0

我有一個名爲Employee的實體,它具有一個名爲Groups的導航屬性。實體的導航屬性是哈希集並且不能綁定到控件

組映射到具有Name屬性的Group實體。

要建立的關係型數據,我實現了這個問題的答案: Columns of two related database tables in one ASP.NET GridView with EntityDataSource

我對員工的實體還包括他們的羣組:

<asp:EntityDataSource ID="GroupsByEmployeeSource" runat="server" ConnectionString="name=SafetyContext" DefaultContainerName="SafetyContext" EnableDelete="True" EnableFlattening="False" EnableInsert="True" EnableUpdate="True" EntitySetName="Employees" Include="Groups" Where="it.[EID] == @EmpID"> 
    <WhereParameters> 
     <asp:ControlParameter Name="EmpID" Type="Int32" ControlID="GridView1" PropertyName="SelectedDataKey.Value" /> 
    </WhereParameters> 
</asp:EntityDataSource> 

我再嘗試綁定在另一個Gridview中的組的名稱:

<asp:GridView runat="server" ID="GridView3" DataSourceID="GroupsByEmployeeSource" AutoGenerateColumns="False"> 
      <Columns> 
       <asp:CommandField /> 
       <asp:TemplateField> 
        <ItemTemplate> 
         <asp:Label ID="GroupsByEmployee" runat="server" Text='<%#Eval("Groups.Name") %>' /> 
        </ItemTemplate> 
       </asp:TemplateField> 
      </Columns> 
     </asp:GridView> 

這會引發錯誤,指出組沒有屬性名稱。在問這個問題之後 - DataBinding: Generic.HashSet`1 does not contain a property with the name我意識到這是因爲Groups是一個HashSet。

public partial class Employee 
{ 
    public Employee() 
    { 
     this.Employee_Action = new HashSet<Employee_Action>(); 
     this.Groups = new HashSet<Group>(); 
    } 

    public long EID { get; set; } 
    public string Manager { get; set; } 
    public string Location { get; set; } 
    public string Name { get; set; } 
    public string SESA { get; set; } 

    public virtual ICollection<Employee_Action> Employee_Action { get; set; } 
    public virtual ICollection<Group> Groups { get; set; } 
} 

在構造函數中,導航性能如HashSets創建:我看着後生成的代碼爲實體對象這更有意義。不幸的是,在閱讀HashSets之後,我意識到它們只能迭代。所以現在我有一個導航屬性,我基本上無法通過我通常將數據綁定到控件的方式訪問。

我不確定我需要做什麼來訪問導航屬性。我是否將生成的代碼更改爲HashSets以外的其他代碼?有沒有辦法通過#Eval()組實際獲得組的屬性而不是HashSet的屬性?我是否應該在#Eval電話中投放羣組?關於如何獲取由實體的導航屬性表示的實體,我非常失望。如果答案是以編程方式進行,那麼我應該使用哪個事件?

回答

0

由於Groups是組項目的集合,因此您實際嘗試在列中顯示什麼?集合中的第一組?或者集合中的所有組用逗號分隔?

你可以試試;

Groups.First().Name

string.Join(",", Groups.Select(g => g.Name).ToArray())