У меня есть запрос, который я хочу вернуть сущность с отфильтрованной навигационной собственностью коллекции. Согласно документу 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
Явно загружая фильтрованное навигационное свойство через Load () не работает ⇐ C#
Место общения программистов C#
1750871040
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);
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79565443/explicitly-loading-filtered-navigation-property-via-load-not-working[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия