[Everything stripped down to highlight the problem]
SchemeRequest
------------------------------
Id
SchemeId [FK to Schemes Table]
------------------------------
using(var scope = new TransactionScope())
{
var request = new SchemeRequest { SchemeId = [schemeId] };
this.dbContext.SchemeRequests.Add(request);
this.dbContext.SaveChanges();
this.mailer.SendMail(request); // request.Scheme is null when it should not be
scope.Complete();
}
I am using EF Model first. Now after the call to SaveChanges the Navigation property Scheme in SchemeRequest is null. I am not sure why. Can anyone help? There is another navigation property which seems to work fine. How do I debug this ie how do I find out whats happening behind the scenes.?
I checked and doublechecked the relationships, properties etc but everything seems to be ok.
It’s not expected that the navigation property is loaded. You only save a new entitiy without setting its navigation property. EF does not load another entity automatically when you save the parent.
However, the navigation property would be set in two situations:
The
Schemewith theSchemeIdyou set in the newSchemeRequestis already loaded and attached to the context. EF would fix the relationship automatically and set the navigation property.If you use lazy loading the navigation property would be loaded after setting the
SchemeIdas soon as you access it. However, you need to create the newSchemeRequestas a lazy loading proxy instead of usingnew: