2
我在我的数据库中这两个表,现在用的是实体框架,这个样本使用存储库模式
我有一个下面IRepository接口定义获取有关表的实体框架
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;
}
}
在我的代码中,我正在实例化一个QuestionsRepository,并且我还想获得所有返回的问题列表的相关答案。我想知道完成这件事的好方法是什么?我是否在GetAllWithChild(String ChildName)
这样的界面中创建了另一个功能?我认为有更好的方法去做这件事。
你有返回DbSet并调用该方法。您必须使用Include(扩展方法)。由于延期执行的优势,您的查询将会触发一次,您将得到您想要的任何内容。 –
哦,是的,让我编辑代码。我正在测试它与一个子表 – Farax
你必须使用像这样新的QuestionsRepository()。GetAll()。Include(“Answers”)。ToList() –