【问题标题】:In EF Core how to select specific column and also save在 EF Core 如何选择特定列并保存
【发布时间】:2018-08-02 21:33:22
【问题描述】:

我有以下 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();

}

【问题讨论】:

  • 该链接是关于如何选择特定属性的..这不是我要找的..我认为@David Browne 的答案是我要找的..我还没有尝试过跨度>
  • 如果您经常想从数据库中获取“MyTable”数据而不拖拽 XML 内容,我会选择表格拆分。很容易忘记应该明确排除 XML 内容,尤其是。当项目中有更多开发人员时。
  • 我喜欢表格拆分选项。我以前从未尝试过,但我会尝试一下

标签: entity-framework-core ef-core-2.0


【解决方案1】:

除了将内容视为单独的相关实体的表拆分之外,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();

}

【讨论】:

    【解决方案2】:
    1. 您应该创建一个包含所需列的新类
    2. 使用自动映射器

    检查自动映射器文档 这对我有用:

    var teacher = _mapper.ProjectTo<TeacherReadDto>(_applicationDb.Teachers.Where(x=>x.Id==id));
    

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 2012-07-31
      • 1970-01-01
      • 2021-09-14
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      相关资源
      最近更新 更多