11

I only want to update a field based on the condition that is mentionned below. I know how to write it in SQL. I'm not sure how to accomplish this in entity framework.

UPDATE Table SET SomeDateTime = @NewDateTime WHERE Id = @MyId AND SomeDateTime > @NewDateTime

I want to use this particular query due to using a micro service architecture.

6
  • 2
    maybe you are looking for this extension: entityframework-extensions.net/bulk-update Commented May 24, 2019 at 8:04
  • Is Id a primary key? Commented May 24, 2019 at 8:17
  • @Kevin have you tried to use ExecuteSqlCommand? give a check my answer. Commented May 24, 2019 at 9:20
  • 1
    @AlexandreRodrigues I was hoping to avoid that ... However, that is looking like the best answer .. so far anyway. Commented May 24, 2019 at 10:57
  • 2
    Though legal, that quite much throws away the reason to use Entity at all. Commented May 24, 2019 at 12:24

5 Answers 5

10

If you want use sql directly you can use ExecuteSqlCommand

If you were handling a object and then doing a update I would change a object and call SaveChanges, but that's not the case.. here is an update directly to the table, If that table has millions of rows you want perform sql to get performance on that.

example

using(var context = new SampleContext())
{
    var commandText = "UPDATE Table SET SomeDateTime = @NewDateTime WHERE Id = @MyId AND SomeDateTime > @NewDateTime";
    var newDateTime = new SqlParameter("@NewDateTime", myDateValue);
    var myId = new SqlParameter("@MyId", myIdValue);

    context.Database.ExecuteSqlCommand(commandText,  new[]{newDateTime,myId});
}
Sign up to request clarification or add additional context in comments.

1 Comment

Do not forget to add using Microsoft.EntityFrameworkCore.Relational;
7

Starting from EF Core 7, you can use new method ExecuteUpdate / ExecuteUpdateAsync:

context.Table
   .Where(t => t.Id == myId && t.SomeDateTime > newDateTime)
   .ExecuteUpdate(b => b.SetProperty(x => x.SomeDateTime, x => newDateTime));

1 Comment

For multiple properties you can chain them SetProperty(x => x.SomeDateTime, x => newDateTime).SetProperty(x => x.SomeInt, x => 123)
2

If Id is a primary key, which means you only find one record with it, then the way I'd update it is retrieving the record, changing the value of the properties I want to edit, then saving the changes on the context.

int MyId = ...
DateTime NewDateTime = ...

using (YourDbContext dbContext = new YourDbContext())
{
   YourObject obj = dbContext.YourObjects.SingleOrDefault(item => item.Id == MyId && item.SomeDateTime > NewDateTime)
   if (obj != null)
   {
      obj.SomeDateTime = NewDateTime;
      dbContext.SaveChanges();
   }
}

3 Comments

This will only update individual records by their primary key value (possibly with optimistic concurrency too) instead of updating multiple records using arbitrary criteria.
OP mentioned an Id in their query, which I suppose is the primary key, so of course that updates only one record. I don't understand your point, sorry.
@StackLloyd Indeed. I only looked at the question's title and didn't read the body of his post :D I just made the incorrect assumption they were looking to update multiple records using Linq/EF.
0

I would do this this way:

 try
            {
               var usersToUpdate = await dbContext.MyList.Where(x=>x.Id==myId).ToListAsync();

               usersToUpdate.ForEach(x=>{..make updates..});

                await dbContext.SaveChangesAsync();
            }
            catch (Exception e)
        {
           ..Error handling..
        }

P.S if you want to see how many records where updated you can assign a variable to saveChangesAsync:

var result= await dbContext.SaveChangesAsync();

Comments

0

You can use the following sample code to find a specific record of the database and then update it with the help of EF Core:

public bool UpdateTable()
{
    DatabaseContext _db = new DatabaseContext(); //database context instance
    int MyId = 100; //sample Id
    DateTime MyDateTime = new DateTime(2019, 5, 24, 12, 30, 52); //sample DateTime
    var p = _db.Table.Where(x => x.Id == MyId && x.SomeDateTime > 
        MyDateTime ).FirstOrDefault(); //the targeted record of the database
    if (p != null)
    {
       p.SomeDateTime = DateTime.Now;
       _db.SaveChanges();
       return true;
    }
    return false;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.