Blog

Filter posts by the Tags of Blog section!

How to query over Icollection<> of a type with linq Tuesday, 18 June 2013

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!

 

comments powered by Disqus