How to select item with specific item in iCollection property?

c# entity-framework entity-framework-6

Question

The following class is mine:

 public class Foo
    {
        [Key] 
        public int ID { get; set; }

        public virtual ICollection<Cat> Cats { get; set; }
    }

I'm attempting to choose all Foo objects that include a certain Cat object. I'm currently performing these things:

Cat  c = new Cat(10);
var lPs = Bd.Foos.Include("Cats").Where(p => SomeConditions).ToList();
var lFilter = lPs.Where(p => p.Cats.Contains(c)).ToList();

This method does not appeal to me since I import too many items from the DB simply to use LinQ to filter them.

Exists a better (more effective) approach?

If applicable, the DBcontext is specified as follows:

modelBuilder.Entity<Foo>().HasMany(p => p.Cats).WithMany();
1
0
9/14/2016 9:50:10 PM

Accepted Answer

When you callToList() 2 times. You run the query expression and load the results to the lps variable when you use ToList in the second line of your code. In the next line, you apply the filter to the data that is in memory.

You may omit the initialToList() call that merges the filtering code to a single line and performs the query phrase.

var catIdToCheck = 10;  
var result = db.Foos.Where(g=>g.Cats.Any(y=>y.Id==catIdToCheck)).ToList();
2
9/14/2016 9:54:47 PM


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