Update multiple records using single LINQ query in ASP.Net

asp777
 
on May 21, 2020 01:45 AM
2307 Views

How to update multiple record using single query in linq c#.Please provide solution

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on May 21, 2020 02:05 AM
on May 21, 2020 02:06 AM

Hi asp777,

Refer below sample.

Database

I have made use of the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.

I have already inserted few records in the table.

You can download the database table SQL by clicking the download link below.

Download SQL file

HTML

<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="CustomerId" HeaderText="Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>
<br />
<asp:Button Text="Update" runat="server" OnClick="OnUpdate" />

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        using (CustomerEntities db = new CustomerEntities())
        {
            gvCustomers.DataSource = db.Customers.ToList();
            gvCustomers.DataBind();
        }
    }
}

protected void OnUpdate(object sender, EventArgs e)
{
    using (CustomerEntities db = new CustomerEntities())
    {
        db.Customers.ToList().ForEach(c =>
        {
            c.Country = "Test";
        });
        db.SaveChanges();
    }

    Response.Redirect(Request.Url.AbsoluteUri);
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Using db As CustomerEntities = New CustomerEntities()
            gvCustomers.DataSource = db.Customers.ToList()
            gvCustomers.DataBind()
        End Using
    End If
End Sub

Protected Sub OnUpdate(ByVal sender As Object, ByVal e As EventArgs)
    Using db As CustomerEntities = New CustomerEntities()
        db.Customers.ToList().ForEach(Function(c)
                                            c.Country = "Test"
                                        End Function)
        db.SaveChanges()
    End Using

    Response.Redirect(Request.Url.AbsoluteUri)
End Sub

Screenshot