gpt4 book ai didi

entity-framework-core - 在 EF Core 中如何选择特定列并保存

转载 作者:行者123 更新时间:2023-12-04 01:58:37 25 4
gpt4 key购买 nike

我有以下 SQL 表

 ID INT  
Status NVARCHAR(50)
FileContent XML

使用 EF Core 我想选择 IDStatus 列但不加载 XML 列。 (因为 xml 数据可能很大,我不想将它加载到内存中,而且我正在执行的业务逻辑不需要它)然后设置 Status

public async Task DoSomwthing(int id)
{
// select only needed columns
var result = await _dbContext.MyTable
.Where(x=>x.ID == id)
.Select(x=> new
{
ID = x.ID,
Status = x.Status
})
.SingleOrDefaultAsync();

// do something here using result

// Since i am not loading the complete entity
// How do i set the Status here to new value


//Save the tracked changes
await _dbContext.SaveChangesAsync();

}

最佳答案

除了将内容视为单独的相关实体的表拆分之外,EF 还支持只更新选定的列。

因此您可以使用其属性的子集构造一个实体,然后将未检索的属性标记为未更改。例如:

public async Task DoSomething(int id)
{
// select only needed columns
var result = await this.Foos
.Where(x => x.ID == id)
.Select(x => new Foo
{
ID = x.ID,
Status = x.Status
})
.SingleOrDefaultAsync();


result.Status = 2;

this.Entry(result).State = EntityState.Modified;
this.Entry(result).Property(nameof(Foo.Content)).IsModified = false;

//Save the tracked changes
await this.SaveChangesAsync();

}

关于entity-framework-core - 在 EF Core 中如何选择特定列并保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48937489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com