日期:2014-05-20  浏览次数:21053 次

在 LINQ to Entities 查询中无法构造实体或复杂类型

//取出文章分类,和分类相应的10篇文章
            var query = from t1 in context.Category                        
                        select new
                        {
                            Category,//分类
                            Article = (from t2 in context.Article//文章
                                       orderby t2.ModifiedDate descending
                                       where t2.Category.CategoryID == t1.CategoryID
                                       select new Article { ArticleID = t2.ArticleID, Title = t2.Title }).Take(10)
                                        //如果 new Article { ArticleID = t2.ArticleID, Title = t2.Title } 改成
                                       //select t2 就是正常的,但我不只想取出标题和ID,不想全部取出(性能低)

                        };

            var CategoryList = new List<Category>();
            if (query != null)
            {
                foreach (var i in query)//这里出错
                {

                    foreach (var j in i.Article)
                    {

                        i.Category.Article.Attach(j);//给分类的Article集合属性 Attach 文章

                    }

                    ProductResult.Add(i.Category);

                }
            }
            return CategoryList;


------解决方案--------------------
 Article = (from t2 in context.Article//文章
                                       orderby t2.ModifiedDate descending
                                       where t2.Category.CategoryID == t1.CategoryID
                                       select new Article { ArticleID = t2.ArticleID, Title = t2.Title }).ToList().Take(10)
试试 这样