Question

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.

Was it helpful?

Solution

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top