【发布时间】:2023-03-27 00:25:02
【问题描述】:
当我使用这个查询和实体模型时,一切正常:
var categories = _context.ProductCategories.Include(e => e.Children).ToList();
var topLevelCategories = categories.Where(e => e.ParentId == null);
return View(topLevelCategories);
实体模型:
public class ProductCategory
{
public int Id { get; set; }
public int SortOrder { get; set; }
public string Title { get; set; }
[ForeignKey(nameof(ParentCategory))]
public int? ParentId { get; set; }
public ProductCategory ParentCategory { get; set; } //nav.prop to parent
public ICollection<ProductCategory> Children { get; set; } //nav. prop to children
public List<ProductInCategory> ProductInCategory { get; set; }
}
...但是当我尝试改用视图模型时,我收到以下错误消息:
“InvalidOperationException:传递到 ViewDataDictionary 的模型项的类型为 'System.Collections.Generic.HashSet1[MyStore.Models.ProductCategory]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable1[MyStore.Models.ViewModels.ViewModelProductCategory]'。”
我知道发送到视图的模型不正确,但我不明白为什么。
我的视图模型查询:
var VMCategories = _context.ProductCategories
.Include(e => e.Children).ToList()
.OrderBy(s => s.SortOrder)
.Where(r => r.ParentId == null)
.Select(v => new ViewModelProductCategory
{
Id = v.Id,
Children = v.Children,
ParentId = v.ParentId,
Title = v.Title,
SortOrder = v.SortOrder
})
.ToList();
return View(VMCategories);
视图模型:
public class ViewModelProductCategory
{
public int Id { get; set; }
public int? ParentId { get; set; }
public string Title { get; set; }
public int SortOrder { get; set; }
public string ProductCountInfo =>
Products != null && Products.Any() ? Products.Count().ToString() : "0";
public ProductCategory ParentCategory { get; set; } // Nav.prop. to parent
public IEnumerable<ProductCategory> Children { get; set; } // Nav.prop. to children
public List<ViewModelProduct> Products { get; set; } // Products in this category
public List<ViewModelProduct> OrphanProducts { get; set; } // Products with no references in ProductInCategory
}
索引视图:
@model IEnumerable<MyStore.Models.ViewModels.ViewModelProductCategory>
<ul>
@Html.Partial("_CategoryRecursive", Model)
</ul>
_CategoryRecursive.cshtml:
@model IEnumerable<MyStore.Models.ViewModels.ViewModelProductCategory>
<ul style="list-style:none;padding-left:0px;">
@if (Model != null)
{
foreach (var item in Model)
{
if (item.Children != null)
{
<li>
<ul>
@Html.Partial("_CategoryRecursive.cshtml", item.Children)
</ul>
</li>
}
}
}
</ul>
我的错误在哪里?
【问题讨论】:
-
“我无法让它工作:”不是问题陈述。你到底遇到了什么问题?
-
研究异常,添加
.ToList()。 -
@CamiloTerevinto 请查看更新。
-
视图顶部声明的模型类型是什么?
-
ViewModelProductCategory类的子属性仍然是public IEnumerable<ProductCategory>类型,这就是为什么在渲染局部视图_CategoryRecursive.cshtml本身时会出错的原因。您需要将 Children 属性更改为IEnumerable<ViewModelProductCategory>并正确填充它。
标签: c# linq entity-framework-core