【问题标题】:Update A Table From A List从列表更新表
【发布时间】:2021-04-29 19:40:38
【问题描述】:
我有两张桌子。其中一个是数据库中的客户,另一个是来自用户的 ChangedCustomers。我写了更新的模型,我猜是少了点什么。
public async Task<int> UpdateCustomers (IENumerable<ChangedCustomers> changedCustomers
{
foreach(var item in changedCustomers)
{
_context.Customers.Updaate (new Customers()
{
CustomerName=item.CustomerName,
CustomerAddress=item.CustomerAddress
});
}
return await _context.SaveChangesAsync();
}
在方法中,我并不是说“当客户表和 ChangedCustomers 表中的 Id 值相等时更新该行”。我需要这个,但我做不到。我该怎么做?
【问题讨论】:
标签:
c#
.net
entity-framework
【解决方案1】:
您正在尝试通过添加新行来更新该行?这就是它的样子。如果要更新特定行,则需要获取该行,然后更新值。
foreach (var item in changedCustomers)
{
var customer = _context.Customers
.FirstOrDefault(x => x.CustomerId == item.CustomerId);
if (customer != null)
{
customer.CustomerName = item.CustomerName;
customer.CustomerAddress = item.CustomerAddress;
}
else
{
customer = new Customer
{
CustomerName = item.CustomerName,
CustomerAddress = item.CustomerAddress
}
_context.Add(customer);
}
}
_context.SaveChangesAsync();
FirstOrDefault() 将从_context.Customers 中检索与表达式匹配的第一个值,如果找不到,则默认为空。如果不为null,则可以进行更改,如果为null,则可以添加一个新值。
【解决方案2】:
以下是更新可放置在循环中的现有记录的一般逻辑:
//Find the entity already tracked based on table key
var entity = context.Customers.FirstOrDefault(item => item.YourTableID == id);
// Validate entity is not null
if (entity != null)
{
// Make changes to specific field
entity.Name = "Me";
// Update entity in it's entirety
entity = new Customers() { //Your logic here to build the updated entity }
// Save changes in database
context.SaveChanges();
}
【解决方案3】:
只需将实体标记为已修改并调用SaveChanges。
只会执行UPDATE sql 查询。
@jaabh 答案中的代码效率非常低,因为它预先执行 sql 查询 SELECT,从数据库中读取我们已经拥有的那些实体。这是不必要的。
public async Task<int> UpdateCustomers(IEnumerable<ChangedCustomers> changedCustomers)
{
foreach (var item in changedCustomers)
{
_context.Entry(item).State = EntityState.Modified;
}
return await _context.SaveChangesAsync();
}