How to query over Icollection<> of a type with linq

When you are implementing many to many relation in SQL, in the case of using entity framework code fist you must use Icollection<> or Ilist<> of an entity. Imagine that you have this classes , an Author class which has a collection of books

  1.     public class Author
  2.     {
  3.         public int Id { get; set; }
  4.         public string FirstName { get; set; }
  5.         public string LastName { get; set; }
  6.  
  7.         public ICollection<Books> Books { get; set; }
  8.     }

And the Books which has a collection of Authors

  1.     public class Books
  2.     {
  3.         public int Id { get; set; }
  4.         public string Title { get; set; }
  5.  
  6.         public ICollection<Author> Authors { get; set; }
  7.     }

And this is your context class

  1.     public class ContextClass : DbContext
  2.     {
  3.         public DbSet<Books> Books { get; set; }
  4.         public DbSet<Author> Authors { get; set; }
  5.     }

If you want you create a repository class, to get the books by authors Id, You should act like this

  1.     public class Repository
  2.     {
  3.         private ContextClass _contextClass = new ContextClass();
  4.         public IEnumerable<Books> FindBookByAuthor(int authorId)
  5.         {
  6.             var query = _contextClass.Books.Where(b => b.Authors.Any(a => a.Id == authorId));
  7.             return query.ToList();
  8.         }
  9.     }

In lambda expression you have to use any(), because you have a collection of authors in book class. That's all!

 


Tags: C# Linq


comments powered by Disqus