Search code examples
asp.netentity-frameworkdata-bindinggridviewdatabound-controls

Using databound controls to obtain sum from column in related entity in Databound Gridview


I have a gridview that is bound to a datasoure on page load. The datasource is connected to various other database tables, ie. datasourceItem.relatedEntity

There is a column in the gridview whose value is dependent upon the sum of a certain field in all related relatedEntities.

So dataSourceItem has a one to many relationship with relatedEntity, and I need to sum the value from a specific column in all related relatedEntities. I want to do this as simply as possible, and I know this syntax is wrong, but this is kind of what I wanted to do:

Markup:

<asp:TemplateField HeaderText="Sum">
     <ItemTemplate>
         <asp:Label ID="lblSum" runat="server" Text='<%# Bind("relatedEntity.ColumnName").Sum() %>' />
     </ItemTemplate>
</asp:TemplateField>

Code-behind (databinding):

myGridview.DataSource = from ds in DataContext.dataSource
                        where ds.Id == selectId
                        select ds;
myGridview.DataBind();

I want to keep the amount of code to a minimum, so if this is at all possible, please help me figure out how. To be clear, the line of code I want to make work is this:

'<%# Bind("relatedEntity.ColumnName").Sum() %>'

Or at least something to that effect. I don't necessarily have to use the Sum() method... if there is a different/better way of handling this, feel free to let me know


Solution

  • First you need to use Eval instead of Bind. Next, you need to cast the evaluated expression to your EntityCollection type

    <asp:Label ID="lblSum" runat="server" Text='<%# ((System.Data.Objects.DataClasses.EntityCollection<relatedEntityItemType>)Eval("relatedEntity")).Sum(i=>i.ColumnName) %>'></asp:Label>
    

    Also you need to the proper imports <%@ Import Namespace="YourEntitiesNamespace" %> and System.Data.Entity

    Edit: If the page is doesn't compile, this is needed in web.config

    <compilation targetFramework="4.0">
         <assemblies>
         <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>            
          </assemblies>
    </compilation>
    

    Also you can get rid off the full name of the type using the import directive

    <%@ Import Namespace="..entities.." %>
    <%@ Import Namespace="System.Data.Objects.DataClasses" %>