Ehsan Ghanbari

Experience, DotNet, Solutions

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

When you are implementing many to many relations 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


    public class Author
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public ICollection<Books> Books { get; set; }


And the Books which has a collection of Authors


    public class Books
        public int Id { get; set; }
        public string Title { get; set; }

        public ICollection<Author> Authors { get; set; }


And this is your context class


    public class ContextClass : DbContext
        public DbSet<Books> Books { get; set; }
        public DbSet<Author> Authors { get; set; }


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


    public class Repository
        private ContextClass _contextClass = new ContextClass();
        public IEnumerable<Books> FindBookByAuthor(int authorId)
            var query = _contextClass.Books.Where(b => b.Authors.Any(a => a.Id == authorId));
            return query.ToList();


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


About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in MVC4
How to use PagedList In MVC
Redis as a cache server
Domain driven design VS model driven architecture
What's the DDD-lite?
Multiple submit buttons in MVC
comments powered by Disqus