Explizit laden filtrierte Navigationseigenschaft über Load () funktioniert nicht
Posted: 10 Apr 2025, 01:14
Ich habe eine Anfrage, die ich ein Unternehmen mit einer gefilterten Sammelnavigationseigenschaft zurückgeben möchte. Gemäß dem EF6 -Dokument sollte ich es durch explizites Laden laden können. Nachdem der Kontext entsorgt wurde, erhalte ich jedoch den folgenden Fehler, wenn ich versuche, auf die Navigationseigenschaft draußen zuzugreifen. Die Navigationseigenschaft vor dem Kontext wird entsorgt, und es wird das faule Laden ausgelöst, und ProductVariants wird ohne Fehler korrekt geladen. Ich frage mich jedoch, warum load () nicht funktioniert?
Code: Select all
void RouteToVariant() {
Product product = productDAO.FindByProductKeyWithVariantsByCustomer(productKey, variantType);
// exception thrown here
int ProductVariantID = product.ProductVariants.ProductVariantID;
}
// The method in the DAO class
public Product FindByProductKeyWithVariantsByCustomer (int productKey, string variantType) {
using (var context = new MyDbContext())
{
var product = context.Products
.Find(productKey);
/* Also tried .ToList() instead of .Load()
and assign the list to product.ProductVariants but didn't work */
context.Entry(product)
.Collection(p => p.ProductVariants)
.Query()
.Where(pv => pv.VariantType == variantType)
.Load();
return product;
}
}
< /code>
und die Entitäten: < /p>
public class Product {
[Key]
public int ProductKey {get;set;}
public virtual ICollection ProductVariants {get;set;}
}
public class ProductVariant {
[Key]
public int ProductVariantID {get;set;}
public int ProductKey {get;set;}
public Product Product {get;set;}
public string VariantType {get;set;}
}
// and the fluent API in another class for configuring the relation
public ProductVariantConfiguration()
{
HasRequired(m => m.Product)
.WithMany(o => o.ProductVariants)
.HasForeignKey(m => m.ProductKey);
}