简体   繁体   English

比较int时Linq to Entities错误? 值

[英]Linq to Entities error when comparing int? to a values

I am trying to write a recursive function that will traverse a tree. 我试图编写一个遍历树的递归函数。 I have my entity 'Folder' with two properties of ParentFolderID and FolderID. 我的实体“文件夹”具有ParentFolderID和FolderID的两个属性。 If the folder is at root level, then its ParentFolderID is null. 如果文件夹位于根级别,则其ParentFolderID为null。 I created a recursive function that accepts a paramater ID and adds returns all the folder entities with the same ParentFolderID as ID, but I'm getting the error of 'Unable to create a constant value of type 'System.Object'. 我创建了一个递归函数,该函数接受参数ID并添加返回与ID具有相同ParentFolderID的所有文件夹实体,但是出现了“无法创建类型为System.Object”的常量的错误。 Only primitive types or enumeration types are supported in this context.'. 在这种情况下,仅支持原始类型或枚举类型。

Here is my function: 这是我的功能:

    private List<Folder> GetFolderChildren(int? folderId)
    {
        var childFolders = new List<Folder>();

        //  finalList is List<> that is actually returned
        var finalList = new List<Folder>();

        //  Your looking at the root level folder
        if (folderId == null)
        {
            childFolders = DocumentEntities.Folders.Where(x => x.ParentFolderID.Equals(folderId)).ToList();
        }
        else
        {
            childFolders = DocumentEntities.Folders.Where(x => x.ParentFolderID == folderId).ToList();
        }

        //  If there are no childFolders, then you've hit the bottom of this branch.  Return this folder.
        if (!childFolders.Any())
        {
            finalList.Add(DocumentEntities.Folders.SingleOrDefault(x => x.FolderID == folderId));
        }
        else
        {
            foreach (var childFolder in childFolders)
            {
                finalList.AddRange(GetFolderChildren(childFolder.FolderID, pageName));
            }

            //  Now that you've gone through this folders children, add this folder
            finalList.Add(DocumentEntities.Folders.SingleOrDefault(x => x.FolderID == folderId));
        }

        return finalList;
    }

It never reaches the foreach when the folderID is null nor when its an int. 当folderID为null或int时,它永远不会到达foreach。 Any ideas? 有任何想法吗?

If the x.ParentFolderID is null , you will not get access in the Equals method because it is null. 如果x.ParentFolderIDnull ,则您将无法通过Equals方法访问它,因为它为null。 Try to compare the entire value with the argument since it has the same type, for sample 尝试将整个值与参数进行比较,因为它的类型相同,例如

childFolders = Entities.Folders.Where(x => x.ParentFolderID == folderId).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM