Calculate Column Sum using Entity Framework in ASP.Net in C# and VB.Net

Last Reply 4 months ago By pandeyism

Posted 4 months ago

how  to calculate the sum of all the records in this column and display in a label using entity framework. Please help with that also.

Posted 4 months ago Modified on 4 months ago

Hi Rezu2215,

Refer below sample.

Database

For this sample I have used of NorthWind database that you can download using the link given below.

Download Northwind Database

HTML

<asp:Label ID="lblCount" runat="server" />

Namespaces

C#

using NorthwindModel;

VB.Net

Imports NorthwindModel

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        NorthwindEntities entity = new NorthwindEntities();
        decimal? sum = entity.Orders.Select(x => x.Freight).Sum();
        lblCount.Text = "Sum is " + Math.Round(Convert.ToDouble(sum), 2).ToString();
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim entity As NorthwindEntities = New NorthwindEntities()
        Dim sum As Decimal? = entity.Orders.[Select](Function(x) x.Freight).Sum()
        lblCount.Text = "Sum is " & Math.Round(Convert.ToDouble(sum), 2).ToString()
    End If
End Sub

Output

Sum is 65046.85