问题
I've got 2 new entities in an otherwise working app, I've trimmed unrelated properties (everything is marked virtual):
QuoteOverrideRequest
public virtual int RequestedById { get; set; }
public virtual int QuoteId { get; set; }
public virtual int StatusId { get; set; }
//nav properties
public virtual Customer RequestedBy { get; set; }
public virtual Quote Quote { get; set; }
public virtual QuoteOverrideRequestStatus Status { get; set; }
All 3 navigation properties are mapped the same way. When I create a new QuoteOverrideRequest and insert it, RequestedBy and Quote are auto populated with their entities. Status is not.
QuoteOverrideRequest request = new QuoteOverrideRequest();
request.QuoteId = quoteId;
request.RequestedById = _workContext.CurrentCustomer.Id;
request.StatusId = 1;
_quoteService.InsertOverrideRequest(request);
The insert function is calling a Repository that adds the object to a DbSet and calls the DbContext.SaveChanges()
I assume the problem is with QuoteOverrideRequestStatus because the other 2 classes lazy load correctly. If I get an instance of that Status earlier in the function, it will show up in the Status property after the insert.
The QuoteOverrideRequestStatus class has a public parameterless constructor and all of it's properties are virtual.
public partial class QuoteOverrideRequestStatus : BaseEntity
{
public QuoteOverrideRequestStatus() { }
public virtual string Name { get; set; }
public virtual int DisplayOrder { get; set; }
}
BaseEntity has the Id property. I've confirmed that Lazy Loading and Proxy Generation are both true on the DbContext when all this runs.
回答1:
new QuoteOverrideRequest()
This is not correct. Lazy loading won't work for properties of models you instantiate using the new
keyword.
You should use db.Set<T>().Create()
where db
is your instance of DbContext
and T
is your model.
This will instantiate the correct proxy object of your model which will enable lazy-loading navigation properties.
来源:https://stackoverflow.com/questions/32747947/ef6-lazy-loading-not-working-for-a-navigation-property