简体   繁体   中英

How to select item with specific item in iCollection property?

I have the following class:

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

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

I am trying to select all the Foo objects which contains a specific Cat object. Currently I am doing this:

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();

I do not like this approach because I bring to many objects from the DB just to filter them using LinQ.

Is there a better(more efficient) way?

if it is useful, the DBcontext is defined in this way:

modelBuilder.Entity<Foo>().HasMany(p => p.Cats).WithMany();

You are calling ToList() 2 times. When you call ToList in your second line, It executes the query expression and load the results to the lps variable. You are doing the filter on the inmemory data in the next line.

You can avoid the first ToList() call which executes the query expression and merge the filtering code to same line.

var catIdToCheck = 10;  
var result = db.Foos.Where(g=>g.Cats.Any(y=>y.Id==catIdToCheck)).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM