1

它加载类别,但始终使用 null 父级。我想获取具有给定 ID 的层次结构类别。

public static Category GetCategory(System.Guid ID, ActionLinkInfo AInfo)
        {
            Category category = null;

            using (TIKSN.STOZE.Data.StozeContext DContext = new Data.StozeContext())
            {
                var cats = from cat in DContext.Categories where cat.ID == ID select cat;

                foreach (Data.Category Cat in cats)
                {
                    category = new Category(Cat, Cat.Parent == null ? null : GetCategory(Cat.Parent.ID, AInfo), AInfo);
                }
            }

            return category;
        }
4

2 回答 2

1

试试这个:

var cats = from cat in DContext.Categories.Include("Parent") where cat.ID == ID select cat;

或者您可以更改模型,将其ParentID作为整数包含在Category类中:

public class Category {

    /* (...) */

    public int ParentID { get; set; }

    [ForeignKey("ParentID")]
    public Category Parent { get; set; }
}

有了它,您无需从数据库Cat.ParentID加载整个对象即可获得。Parent

于 2012-12-31T07:34:33.617 回答
0

解决方案是明确要求加载父母。

public static Data.Entity.Category GetCategory(long ID)
    {
        Data.Entity.Category category;

        using (Data.StozeContext DContext = new Data.StozeContext())
        {
            var categories = from SingleCategory in DContext.Categories.Include("Parent") where SingleCategory.ID == ID select SingleCategory;

            category = categories.Single();
        }

        return category;
    }
于 2015-02-05T10:19:39.347 回答