简体   繁体   English

如何使用实体框架 .NET Core 编写带有 where 子句的 SQL 更新查询

[英]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.我知道如何在 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. 如果Id是主键,这意味着您只能找到一条记录,那么我更新它的方式是检索记录,更改我要编辑的属性的值,然后在上下文中保存更改。

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: PS如果要查看更新的记录数,可以将变量分配给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: 您可以使用以下示例代码查找数据库的特定记录,然后在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 如果要直接使用sql,可以使用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. 如果您正在处理一个对象,然后进行更新,我会更改一个对象并调用SaveChanges ,但事实并非如此......这里是对表的直接更新,如果该表有数百万行,则需要执行sql以获得性能在那。

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 :从 EF Core 7 开始,您可以使用新方法ExecuteUpdate

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 C# 中的实体框架中使用 where 子句编写 SQL 更新查询 - How can i write SQL update query with where clause in Entity Framework in C# 如何在以下LINQ to SQL Query中编写“Where”子句? - How can I write the “Where” clause in the following LINQ to SQL Query? 使用实体框架在 .NET Core 3.1 中进行迁移后,如何更新数据库 model? - How can I update the database model after doing a migration in .NET Core 3.1 using Entity Framework? 如何使用实体框架通过 ASP.NET Core Web API 处理通用查询? - How can I process a generic query through ASP.NET Core Web API using Entity Framework? 如何使用 .NET Core 中的 Entity Framework Core 在日期列中插入和更新 SQL Server DateTime - How to insert and update SQL Server DateTime in a date column using Entity Framework Core in .NET Core 我可以在实体框架核心和 linq 中查询时写 case 吗? - Can I write case when query in entity framework core and linq? 如何向实体框架查询添加 where 子句 - How to add a where clause to Entity Framework query 标记枚举属性where子句不会影响实体框架核心中的sql查询 - flags enum property where clause not affect on sql query in entity framework core Entity Framework Core 6.0.8 动态查询问题的 WHERE 子句 - Entity Framework Core 6.0.8 WHERE clause for dynamic query issues 使用实体框架在 .NET Core 中编写带有子查询的 SQL 查询,该实体框架返回具有不同数量的返回子行的项目列表 - Write a SQL query with a subquery in .NET Core using Entity Framework that returns a list of items with varying number of returned child rows
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM