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