Явно загружая фильтрованное навигационное свойство через Load () не работаетC#

Место общения программистов C#
Ответить
Anonymous
 Явно загружая фильтрованное навигационное свойство через Load () не работает

Сообщение Anonymous »

У меня есть запрос, который я хочу вернуть сущность с отфильтрованной навигационной собственностью коллекции. Согласно документу EF6, я смогу загрузить его с помощью явной загрузки. Однако после устранения контекста я получу следующую ошибку при попытке получить доступ к навигационному свойству. Контекст утилизируется, что он запустит ленивую загрузку, а ProductVariants будет загружен правильно без ошибки. Тем не менее, мне интересно, почему загрузка () не работает?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>
и объекты: < /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);
}


Подробнее здесь: https://stackoverflow.com/questions/795 ... ot-working
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»