首页 > 解决方案 > "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?

标签: linqentity-framework-coreblazor-server-side

解决方案


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;
    }

推荐阅读