0

I am trying to do

IList<Sth> sths= Context.Sth.Where(g => g.IsX == true && g.Y.Name== "name").ToList();  //here it successfully compares  g.Y.Name
            foreach (Sth g in sths)
            {
                Context.Entry(g).Collection(g=>g.Y).Load(); //the exception is thrown here
                this.mylist.Add(g.Y.Id);
            }

I already tried

using System.Data.Entity;
using System.Linq;

.

2
  • 2
    Apparently g.Y is not ICollection<>. Use either .Reference method (instead of .Collection) or better why not eager load it in the main query with Include. Commented Dec 17, 2018 at 11:13
  • 1
    You can include sub entities on the main query using Include learn.microsoft.com/en-us/ef/ef6/querying/related-data Commented Dec 17, 2018 at 11:14

1 Answer 1

2

g.Yis not a collection otherwise you wouldn't be able to call g.Y.Name on the first line. So you should either use Reference instead of collection, or preferably use Include instead. For example:

IList<Sth> sths = Context.Sth
    .Where(g => g.IsX == true && g.Y.Name== "name")
    .Include(g => g.Y)
    .ToList(); 

this.mylist.AddRange(sths.Select(g => g.Y.Id);

But, if all you are trying to do it get the Id property, then you can just do that:

this.mylist.AddRange(Context.Sth
    .Where(g => g.IsX == true && g.Y.Name== "name")
    .Select(g => g.Y.Id));
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! But than, I had to change the IList to IQueryable :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.