我有以下SQL表
ID INT
Status NVARCHAR(50)
FileContent XML
使用EF Core我想选择ID
和Status
列但不加载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();
}
答案 0 :(得分:2)
除了将内容视为单独的相关实体的表拆分外,EF还支持仅选择列的更新。
因此,您可以构造具有其属性子集的实体,然后将未检索的属性标记为未更改。 EG:
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();
}
答案 1 :(得分:-1)
检查自动映射器文档 这对我有用:
var teacher = _mapper.ProjectTo<TeacherReadDto>(_applicationDb.Teachers.Where(x=>x.Id==id));