linq - "Operation is not valid due to the current state of the object." Exception, when I want to retrieve Items
问题描述
I use this method to retrieve Items for a Tree component in Blazor Serverside, In the DAL I have:
public List<TreeItem> GetTreeItems()
{
var tree = new List<TreeItem>();
TreeItem item = new TreeItem()
{
DepartmentID = 0,
CategoryID = 0,
Text = "Root",
Childs = context.Departments.OrderBy(d => d.Order).Select(d => new TreeItem()
{
DepartmentID = d.Id,
CategoryID = 0,
Text = d.Title,
Childs = d.Categories.OrderBy(c => c.Order).Select(c => new TreeItem()
{
DepartmentID = d.Id,
CategoryID = c.Id,
Text = c.Title
}).ToList()
}).ToList()
};
tree.Add(item);
return tree;
}
The TreeItem class is the following, (The model shared by the blazor Component and Dal Class):
public class TreeItem
{
public int DepartmentID { get; set; }
public int CategoryID { get; set; }
public string Text { get; set; }
public List<TreeItem> Childs { get; set; }
}
But when I was to retrieve Items for the tree in the blazor component I get the exception: Operation is not valid due to the current state of the object., admin is the DAL class I inject to Blazor component as follows:
private void GetTreeModel()
{
try
{
Items = admin.GetTreeItems();
TreeSuccess = true;
TreeMessage = "Success";
return;
}
catch (Exception ex) // Error here
{
TreeSuccess = false;
TreeMessage = "Can not load tree items";
return;
}
}
What is this error and How to solve it?
解决方案
I solved my problem using First loading entities and then using Linq to Objects, Like this:
var tree = new List<TreeItem>();
var departments = context.Departments.OrderBy(d => d.Order).ToList();
var categories = context.Categories.OrderBy(c => c.Order).ToList();
TreeItem item = new TreeItem()
{
DepartmentID = 0,
CategoryID = 0,
Text = "Root",
Childs = departments.Select(d => new TreeItem()
{
DepartmentID = d.Id,
CategoryID = 0,
Text = d.Title,
Childs = categories.Where(c => c.DepartmentID == d.Id).OrderBy(c => c.Order).Select(c => new TreeItem()
{
DepartmentID = d.Id,
CategoryID = c.Id,
Text = c.Title
}).ToList()
}).ToList()
};
tree.Add(item);
return tree;
}
推荐阅读
- firebase - Firebase Auth:如何检测到试图自动登录当前用户的 Firebase?
- angular - Angular中父子组件的最佳文件夹结构是什么
- wordpress - 建议我使用带有日期突出显示插件的即将发生的事件的 wordpress 插件
- webpack - angular cli 8 中的 Sass-loader PrependData 使用 custom-webpack 抛出错误
- oracle - 如何通过来自另一个模式的过程动态创建表
- c - 如何通过更改 SQLite3 中现有的 SQL 表,通过单个 SQL 语句添加更多列?
- redis - StackExchange.Redis.RedisConnectionException: '无法连接到 redis 服务器
- ios - 尝试使用 AsyncDisplayKit / Texture 为 ASCollectionNode 重新加载数据
- sql - 使用 Spark 优化 Hive SQL 查询?
- java - 如何在 scriptlet 标记中使用 jstl 标记或 numberFormat 格式化数字