Anandh
Anandh

Reputation: 167

How to make the Linq Query as efficient when select list inside the another select list

Please find my Query below. i have try to run this below query. But query throws with exception due to having select List of object inside the Select clause.

the Error was: LINQ to Entities does not recognize the method 'System.Collections.Generic.List1[TagList] ToList[KBTag](System.Collections.Generic.IEnumerable1[TagList])' method, and this method cannot be translated into a store expression.

//KBArticle class
public class KBArticle{
    public int ArticleId{get;set;}
    public ControlId{get;set;}
    public List<TagList> Tags {get;set;}
}

//TagList class
public class TagList
{
    public int TagId{get;set;}
    public string Name{get;set;}
}

public List<KBArticle> GetArticleList(List<int> controlIds)
{
    using (var entity= new DBContext())
    {
        var kbArticleList = (from article in entity.Article
        where controlIds.Contains(article.ControlId)
        join control in entity.SU_Control on article.ControlId equals control.ControlId
        where article.IsActive &&control.IsActive
        select new KBArtcle{
            ArtcleId=article.ArticleId,
            ControlId=control.ControlId,
            Tags=(from Tag in entity.KbTag where tag.artcleId==article.ArtcileId
                  Select new TagList{
                TagId=Tag.Id,
                TagName=Tag.Name
                }).ToList()    

            }).ToList();

        return kbArticleList;
    }
}    

Can you provide efficient solutionfor above query. I have select List of object within list of object. Is it possible in LinQ.

Upvotes: 0

Views: 279

Answers (1)

Amir Sherafatian
Amir Sherafatian

Reputation: 2083

.ToList() can not be applied to inner queries, you can use AsEnumerable() instead, try this:

Tags = (from Tag in entity.KbTag where tag.artcleId==article.ArtcileId
        Select new TagList{
            TagId=Tag.Id,
            TagName=Tag.Name
        })
        .AsEnumerable()

instead of your inner query to fill tags property.

Upvotes: 1

Related Questions