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. If the folder is at root level, then its ParentFolderID is 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'. 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. Any ideas?
If the x.ParentFolderID
is null
, you will not get access in the Equals
method because it is 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.