[c#] Update records using LINQ

I need to set a value in a table for a subset of rows. In SQL, I would do this:

UPDATE dbo.Person SET is_default = 0 WHERE person_id = 5

Is there a way to do this in LINQ?

I currently use the:

var result = (from p in Context.People....)

notation.

Is there an update method I can use? Or do I have to get all the records, then update them one-by-one in a Foreach?

Is this the most efficient way, if this is even possible?

(from p in Context.person_account_portfolio where p.person_id == personId select p)
   .ToList()
   .ForEach(
       x =>
       x.is_default =
       false);

This question is related to c# linq entity-framework

The answer is


This worked best.

(from p in Context.person_account_portfolio 
 where p.person_id == personId select p).ToList()
                                        .ForEach(x => x.is_default = false);

Context.SaveChanges();

You have two options as far as I know:

  1. Perform your query, iterate over it to modify the entities, then call SaveChanges().
  2. Execute a SQL command like you mentioned at the top of your question. To see how to do this, take a look at this page.

If you use option 2, you're losing some of the abstraction that the Entity Framework gives you, but if you need to perform a very large update, this might be the best choice for performance reasons.


I assume person_id is the primary key of Person table, so here's how you update a single record:

Person result = (from p in Context.Persons
              where p.person_id == 5
              select p).SingleOrDefault();

result.is_default = false;

Context.SaveChanges();

and here's how you update multiple records:

List<Person> results = (from p in Context.Persons
                        where .... // add where condition here
                        select p).ToList();

foreach (Person p in results)
{
    p.is_default = false;
}

Context.SaveChanges();

public ActionResult OrderDel(int id)
    {
        string a = Session["UserSession"].ToString();
        var s = (from test in ob.Order_Details where test.Email_ID_Fk == a && test.Order_ID == id select test).FirstOrDefault();
        s.Status = "Order Cancel By User";
        ob.SaveChanges();
        //foreach(var updter in s)
        //{
        //    updter.Status = "Order Cancel By User";
        //}


        return Json("Sucess", JsonRequestBehavior.AllowGet);
    } <script>
            function Cancel(id) {
                if (confirm("Are your sure ? Want to Cancel?")) {
                    $.ajax({

                        type: 'POST',
                        url: '@Url.Action("OrderDel", "Home")/' + id,
                        datatype: 'JSON',
                        success: function (Result) {
                            if (Result == "Sucess")
                            {
                                alert("Your Order has been Canceled..");
                                window.location.reload();
                            }
                        },
                        error: function (Msgerror) {
                            alert(Msgerror.responseText);
                        }


                    })
                }
            }

        </script>

Yes. You can use foreach to update the records in linq.There is no performance degrade.

you can verify that the standard Where operator is implemented using the yield construct introduced in C# 2.0.

The use of yield has an interesting benefit which is that the query is not actually evaluated until it is iterated over, either with a foreach statement or by manually using the underlying GetEnumerator and MoveNext methods

For instance,

var query = db.Customers.Where (c => c.Name.StartsWith ("A"));
query = query.Where (c => c.Purchases.Count() >= 2);
var result = query.Select (c => c.Name);

foreach (string name in result)   // Only now is the query executed!
   Console.WriteLine (name);

Exceptional operators are: First, ElementAt, Sum, Average, All, Any, ToArray and ToList force immediate query evaluation.

So no need to scare to use foreach for update the linq result.

In your case code sample given below will be useful to update many properties,

 var persons = (from p in Context.person_account_portfolio where p.person_name == personName select p);

//TO update using foreach

foreach(var person in persons)
{
//update property values
}  

I hope it helps...


Yes, you have to get all records, update them and then call SaveChanges.


Strangely, for me it's SubmitChanges as opposed to SaveChanges:

    foreach (var item in w)
    {
        if (Convert.ToInt32(e.CommandArgument) == item.ID)
        {
            item.Sort = 1;
        }
        else
        {
            item.Sort = null;
        }
        db.SubmitChanges();            
    }                   

Just as an addition to the accepted answer, you might find your code looking more consistent when using the LINQ method syntax:

Context.person_account_portfolio
.Where(p => person_id == personId)
.ToList()
.ForEach(x => x.is_default = false);

.ToList() is neccessary because .ForEach() is defined only on List<T>, not on IEnumerable<T>. Just be aware .ToList() is going to execute the query and load ALL matching rows from database before executing the loop.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?

Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF