In EF Core how to select specific column and also save

ef-core-2.0 entity-framework-core

Question

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();

}
1
2
3/13/2018 6:07:59 PM

Accepted Answer

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();

        }
4
2/22/2018 10:43:54 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow