EF Core - 如何更新实体

问题描述 投票:0回答:2

controller.cs 放置函数:

[HttpPut("{id}")]
public async Task<LookupTable> Put(int id, [FromBody] LookupTable lookuptable)
{
    var item = await lookupRepository.UpdateLookup(id, lookuptable);
    return item;
}

我在存储库层有以下功能:

public async Task<LookupTable> UpdateLookup(int id, LookupTable entity)
{
    LookupTable item = await riskDBContext.LookupTables.Where(c => c.LookupId == id).FirstOrDefaultAsync();
    item = entity;
    var result = await riskDBContext.SaveChangesAsync();
    return item;
}

这不会更新。但是,如果我将代码更改为:

public async Task<LookupTable> UpdateLookup(int id, LookupTable entity)
{
    LookupTable item = await riskDBContext.LookupTables.Where(c => c.LookupId == id).FirstOrDefaultAsync();
    item.LookupAttribute = entity.LookupAttribute;
    var result = await riskDBContext.SaveChangesAsync();
    return item;
}

它确实在数据库中更新。为什么会这样?我在

LookupTable
有很多房产。所以我想如果我把
item = entity
所有旧值都将被替换。

有没有一种方法可以更新所有属性而不是一个一个地分配它们?

c# asp.net-core entity-framework-core asp.net-core-webapi
2个回答
2
投票

您可以更新实体并将实体状态设置为

EntityState.Modified
.

确保为

entity
的主键属性提供数据库表中存在的id值。

public async Task<LookupTable> UpdateLookup(int id, LookupTable entity)
{
    riskDBContext.Entry(entity).State = EntityState.Modified;
    
    var result = await riskDBContext.SaveChangesAsync();
    
    return item;
}

参考

将现有但已修改的实体附加到上下文


1
投票

您可以使用

Entry
分配属性。也最好在这里使用
Find

public async Task<LookupTable> UpdateLookup(int id, LookupTable entity)
{
    LookupTable item = await riskDBContext.LookupTables.FindAsync(id);

    riskDBContext.Entry(item).CurrentValues.SetValues(entity);
    var result = await riskDBContext.SaveChangesAsync();
    return item;
}

这种方法的缺点是您必须从数据库中检索实体以进行更新,但从另一方面来说,它不会更新表中的所有字段,而只会更新更改。

© www.soinside.com 2019 - 2024. All rights reserved.