Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In EF Core how to select specific column and also save

I have the following SQL table

 ID INT  
 Status NVARCHAR(50)
 FileContent XML

Using EF Core i want to select ID and Status columns but without loading the XML column. (since the xml data could be large i dont want to load it into memory plus it is not needed for the business logic im doing) and then set the 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();

}
like image 666
LP13 Avatar asked Oct 24 '25 09:10

LP13


1 Answers

In addition to Table Splitting, which treats the content as a separate, related entity, EF supports updates of just selected columns.

So you can construct an entity with a subset of its properties, and then mark the non-retrieved properties as unchanged. 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();

}
like image 79
David Browne - Microsoft Avatar answered Oct 27 '25 02:10

David Browne - Microsoft