Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用DTOList更新表_C#_Entity Framework - Fatal编程技术网

C# 使用DTOList更新表

C# 使用DTOList更新表,c#,entity-framework,C#,Entity Framework,我有两张桌子。其中一个是数据库中的客户,另一个是来自用户的ChangedCustomers。在发送数据库之前,我对ChangedCustomers表进行了一些操作,因此我使用ChangedCustomersDTO。在这些操作之后,我无法更新数据库 public async Task<int> UpdateCustomers (IENumerable<ChangedCustomersDTO> changedCustomers { foreach(var item in

我有两张桌子。其中一个是数据库中的客户,另一个是来自用户的ChangedCustomers。在发送数据库之前,我对ChangedCustomers表进行了一些操作,因此我使用ChangedCustomersDTO。在这些操作之后,我无法更新数据库

 public async Task<int> UpdateCustomers (IENumerable<ChangedCustomersDTO> changedCustomers
{
  foreach(var item in changedCustomers)
  {
    var customer=_context.Customers.FirstOrDefault(x => x.CustomerId == item.CustomerId);
    
    if(customer != null)
    {
      customer.Id=item.Id;
      customer.Name=item.Name;
      customer.Address=item.Address;
    }
    else 
    {
      _context.Customers.Add(new Models.Customers()
     {
      customer.Id=new Guid();
      customer.Name=item.Name;
      customer.Address=item.Address;
     }
    }
  }
return await _context.SaveChangesAsync();
}

您的代码中有几个bug。试试这个:

 var customer=_context.Customers.Where(x => x.Id == item.Id).FirstOrDefault(); 

if(customer != null)
    {
      customer.Name=item.Name;
      customer.Address=item.Address;
     _context.Entry(customer).State=EntityState.Modified;
    }
    else 
    {
      _context.Customers.Add(new Models.Customers 
     {
     Id=new Guid(),
      Name=item.Name,
      Address=item.Address
     }
   }

看起来您的错误是将Customer.Id设置为item.Id。可能没有具有该id的客户,并且此操作是修改,而不是添加。你为什么还要重置id?我比较了一下。我在changedCustomer列表中有4个客户,Customer.Id和item.Id值相等。你可以说“为什么你要更新Id,它不能改变”。当我试图删除customer.Id=item.Id时,它会抛出一个关于主键的错误。那么,item.CustomerId和item.Id是相同的值吗?您已根据item.CustomerId选择了客户,但您正在将其设置为item.id。如何解决此问题,我感到困惑。现在我尝试在没有customer.Id=item.Id;的情况下使用。再次返回零。如果要设置id或CustomerId,则需要进行调整。您几乎从不更改主键。主键不起作用。请将您的客户和更改后的客户发送到,好吗
 var customer=_context.Customers.Where(x => x.Id == item.Id).FirstOrDefault(); 

if(customer != null)
    {
      customer.Name=item.Name;
      customer.Address=item.Address;
     _context.Entry(customer).State=EntityState.Modified;
    }
    else 
    {
      _context.Customers.Add(new Models.Customers 
     {
     Id=new Guid(),
      Name=item.Name,
      Address=item.Address
     }
   }