【问题标题】:Updating multiple rows in database更新数据库中的多行
【发布时间】:2021-05-02 10:37:38
【问题描述】:

我正在尝试更新多行。我的方法正在运行,值应该是。但是数据没有更新,并且该方法返回零。我的 ID 是 guid,因此客户价值每次都会占一行。

public async Task<int> UpdateCustomers (IENumerable<ChangedCustomersDTO> changedCustomers)
{
    foreach(var item in changedCustomers)
    {
        var customer = _context.Customers
                               .Where(x => x.CustomerId == item.CustomerId)
                               .FirstOrDefault();
     
        customer.Name = item.Name;
        customer.Address=item.Address;
    }

    return await _context.SaveChangesAsync();
}

我错过了什么吗?我搜索了这个问题,但总是使用这种方法,但它对我不起作用?有什么地方需要换吗?

【问题讨论】:

  • 您根据CustomerId查询并更改Id的值。哪个属性映射为 EF 中的 Id?
  • 实际上当我更新值时它并没有改变。只有姓名和地址发生变化。我正在编辑方法
  • 您的代码现在看起来不错(当客户为空时保存 NRE),显然问题必须来自您的实体类或映射配置中的一些错误。
  • 这不是真正的代码,因为FirstOrDefault; 不会编译。
  • 你真的坚持这个吗?由于我没有复制和传播实际代码的权限,所以我用类似的变量编写了它。 @tymtam

标签: c# entity-framework linq


【解决方案1】:

最好将数据库的变更方式公布为 实体框架。

用于向数据库添加数据

using (var context = new MyContext())
{
    var book = new Book { Name = "book 1" };
    context.Books.Add(book);
    context.SaveChanges();
}

或者你可以设置EntityState.Modified

using (var context = new MyContext())
{
    var book = new Book { Name = "book 1" };
    context.Entry(book).State = EntityState.Added;
    context.SaveChanges();
}

用于更新数据

public async Task<int> UpdateCustomers (IENumerable<ChangedCustomersDTO> changedCustomers)
{
    foreach(var item in changedCustomers)
    {
        var customer = _context.Customers
                               .Where(x => x.CustomerId == item.CustomerId)
                               .FirstOrDefault();
     
        customer.Name = item.Name;
        customer.Address=item.Address;
        context.Entry(customer).State = System.Data.Entity.EntityState.Modified;
    }

    return await _context.SaveChangesAsync();
}

如果要更新多条具有相似值的记录,可以使用.ForEach

public async Task<int> UpdateCustomers (IEnumerable<ChangedCustomersDTO> changedCustomers)
{
   changedCustomers.ToList().ForEach(a =>
   {
       a.Name = "value1";
       a.Address = "value2";
   });
   return await _context.SaveChangesAsync();
}

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 1970-01-01
    • 2015-04-16
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多