Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 731
Craig Avatar asked Dec 30 '13 02:12

Craig


People also ask

How do you update a record in LINQ?

You can update rows in a database by modifying member values of the objects associated with the LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL UPDATE commands.

Does Entity Framework use LINQ to SQL?

Entity Framework Core uses Language-Integrated Query (LINQ) to query data from the database. LINQ allows you to use C# (or your . NET language of choice) to write strongly typed queries.

Can we use LINQ in TypeScript?

There is a TypeScript library for LINQ. It is called ts-generic-collections-linq. Providing strongly-typed, queryable collections such as: List.

How can we update the values of a collection using LINQ?

How can we update the values of a collection using LINQ in C#? If the collection is a List, then we can make use of ForEach extension method which is available as part of LINQ. Fruit Details Before Update.

Can I use foreach to update the records in LINQ?

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.

Is it possible to update an entity using LINQ?

are you using EF context? Yes, but that's not linq is for. To update an entity you must have to specify the Modified state.

How do I use LINQ to SQL?

LINQ to SQL translates our actions to SQL and submits the changes to the database. Here we will perform Select, Insert, Update and Delete operations on a COURSE table. Create a new item, select the LINQ to SQL classes (as shown in the following figure) and name it Operation.dbml. After clicking the Add button the ContextData file is created.


7 Answers

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();
like image 181
ekad Avatar answered Oct 01 '22 20:10

ekad


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();
like image 22
Craig Avatar answered Oct 01 '22 18:10

Craig


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.

like image 41
ChriPf Avatar answered Oct 01 '22 19:10

ChriPf


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.

like image 21
Steve Avatar answered Oct 01 '22 19:10

Steve


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...

like image 28
ManirajSS Avatar answered Oct 01 '22 19:10

ManirajSS


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

like image 34
MarcinJuraszek Avatar answered Oct 01 '22 19:10

MarcinJuraszek


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();            
    }                   
like image 25
boateng Avatar answered Oct 01 '22 20:10

boateng