All root categories in table have a PCATID of null. The method actually does the job, sets cat to the very root category, but then amazingly fails to return it once it hits return cat;
does some weird jumping in and out of the "if" statement, then again to GetRootCat(cat);
and returns not the root category, but the first parent category of cat.
Call:
listModel.PCATID = GetRootCat(cat).CategoryID;
Method:
private Category GetRootCat(Category cat)
{
if (cat.PCATID != null)
{
cat = repository.Categories.FirstOrDefault(x => x.CategoryID == cat.PCATID);
GetRootCat(cat);
}
return cat;
}
Replace
GetRootCat(cat);
with
return GetRootCat(cat);
It doesn't "fail to return", it returns to itself because it's a recursive call. But when it calls itself, it throws away the return value, and falls through to the return cat
, which gives you the parent of the category you called it with.
This would be more sane:
private Category GetRootCat(Category cat) {
if (cat.PCATID == null) { /* This is the root */
return cat;
} else {
Category parent = repository.Categories.FirstOrDefault(x => x.CategoryID == cat.PCATID);
return GetRootCat(parent);
}
}
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.