2

I have these two tables in my database and am using the entity framework for this sample

enter image description here

I have a following IRepository interface defined

public interface IRepository<T> where T:class
    {
        void Add(T entity);
        void Update(T entity);
        void Delete(T entity);
        IQueryable<T> GetAll();
        T Find(int id);
    }


 public class LINQRepository<T> : IRepository<T> where T: class
    {

        protected DbSet DbSet;


        public LINQRepository(DbContext context)
        {
            DbSet = context.Set<T>();

        }

        void IRepository<T>.Add(T entity)
        {
            DbSet.Add(entity);
        }

        void IRepository<T>.Update(T entity)
        {
            DbSet.Attach(entity);
        }

        void IRepository<T>.Delete(T entity)
        {
            DbSet.Remove(entity);
        }

        IQueryable<T> IRepository<T>.GetAll()
        {

            return DbSet as IQueryable<T>;
        }


        T IRepository<T>.Find(int id)
        {

            return DbSet.Find(id) as T;

        }


    }

In my code, I am instantiating a QuestionsRepository and I would also like to get all the related answers to the list of questions that are returned. I wanted to know what is a good way to get this done? Do I create another function in the interface like GetAllWithChild(String ChildName)? I am supposing there is a better way to go about this.

4
  • in getAll method you have to return DbSet and on calling that method .you have to use Include (extenstion method). due to advantage of deferred execution your query will fired once and you will get whatever you want.. Commented Sep 21, 2013 at 3:21
  • Oh yes, let me edit the code. I was testing it with a child table Commented Sep 21, 2013 at 3:22
  • 2
    you have to use something like this new QuestionsRepository().GetAll().Include("Answers").ToList() Commented Sep 21, 2013 at 3:27
  • Can you place your comment in the answers section? I totally feel like a fool posting this question, missed such a trivial thing :) Thanks for pointing it out. Commented Sep 21, 2013 at 3:27

1 Answer 1

3

in getAll method you have to return DbSet and on calling that method .you have to use Include (extenstion method). due to advantage of deferred execution your query will fired once and you will get whatever you want..

you have to use something like this

new QuestionsRepository().GetAll().Include("Answers").ToList();

or

new QuestionsRepository().GetAll().Include(x => x.Answers).ToList();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.