I have these two tables in my database and am using the entity framework for this sample
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.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.