Entity Framework 6 error - ICollection does not contain a definition for sub-entity

asp.net-mvc-5 c# entity-framework-6

Question

I'm using Entity Framework 6 with MVC and I'm using this query in the controller:

        using (var context = new MyDbContext())
        {

            IQueryable<ContentArticle> query;


            query = context.ContentArticle.Where(
                    c => c.ContentArticleSubdivisions.Subdivisions.Name == subdivision

The compiler is complaining that

'System.Collections.Generic.ICollection<MySite.DAL.Models.ContentArticleSubdivision>' does not contain a definition for 'Subdivisions'

However my content article model includes this property:

public virtual ICollection<ContentArticleSubdivision> ContentArticleSubdivisions { get; set; }

and my content article subdivision model includes this:

public partial class ContentArticleSubdivision
{
    ...

    public virtual ICollection<Subdivision> Subdivisions { get; set; }
}

so what am I doing wrong? I think I need to modify the query so that it's looking up all possible Subdivisions that could be contained in the ContentArticleSubdivisions collection?

1
1
7/10/2014 1:11:23 AM

Accepted Answer

You need to use some sort of collection based method to do that. I'm not exactly sure what you are trying to query for here. I'm going to assume you want all articles where a subdivision exists matching that name.

query = context.ContentArticle.Where(
    c => c.ContentArticleSubdivisions.Any(cs => cs.Subdivisions.Any(s => s.Name == subdivision))
);

You can also simplify this using the query comprehension syntax like so

query = from ca in context.ContentArticle
        from cas in ca.ContentArticleSubdivisions
        from s in cas.Subdivisions
        where s.Name == subdivision
        select ca;
1
7/10/2014 1:15:39 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow