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() –