I’m trying to disable tracking for related children entities. I have a model like below (simplified):
public class Request
{
public Guid Id { get; set; }
public int StatusId { get; set; }
public List<RequestAnswer> RequestAnswers { get; set; } = [];
}
public class RequestAnswer
{
public int Id { get; set; }
public string? Answer { get; set; }
public Guid RequestId { get; set; }
public int QuestionId { get; set; }
public Question Question { get; set; }
public Request Request { get; set; }
}
public class Question
{
public int Id { get; set; }
public string Prompt { get; set; }
public List<RequestAnswer> RequestAnswers { get; set; } = [];
}
The context is setup like so:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Ref: RequestAnswer.RequestId > Request.Id
modelBuilder.Entity<Request>()
.HasMany(e => e.RequestAnswers)
.WithOne(e => e.Request)
.HasForeignKey(e => e.RequestId)
.HasPrincipalKey(e => e.Id);
// Ref: RequestAnswer.QuestionId > Question.Id
modelBuilder.Entity<Question>()
.HasMany(e => e.RequestAnswers)
.WithOne(e => e.Question)
.HasForeignKey(e => e.QuestionId)
.HasPrincipalKey(e => e.Id);
}
When I query a request with their answers, I need to get the corresponding question entity as well (there are more fields that I actually need). So my quesry is like so:
var request = _db.Requests.Where(r => r.Id == id)
.Include(r => r.RequestAnswers)
.ThenInclude(a => a.Question)
.FirstOrDefault();
This works well because now I can loop over the answers and access answer.Question.Prompt
. I then need to update the status, so after I do request.StatusId = 2;
I then call _db.Requests.Update(request); _db.SaveChanges();
EF does update the Request record. The problem is that EF then updates all of the RequestAnswers
(which I don’t mind), but also the related Question
database records (to the same values as nothing has been actually changed). Is there a way to load the Request
and Answers
and keep tracking them, but not tracking the related Question
entities? As far as I understand .AsNoTracking
is all or nothing for one query result.
The main issue is the user running this piece of code only has SELECT
permissions on the Question table and SELECT/INSERT/UPDATE
on the other 2 tables, so updating the Request
entity fails.
I am using .net 8 and EF Core 8.
I could load the Question records separately as no tracking but I would then need to match them manally with the questions and pass them around separately which I’m trying to avoid.
Maxime Claudel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.