简体   繁体   中英

How can I write a SQL update query with a where clause using Entity Framework .NET Core

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.

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();
   }
}

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

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

var result= await dbContext.SaveChangesAsync();

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;
}

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});
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM