2

我在我的数据库中这两个表,现在用的是实体框架,这个样本使用存储库模式

enter image description here

我有一个下面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)这样的界面中创建了另一个功能?我认为有更好的方法去做这件事。

+0

你有返回DbSet并调用该方法。您必须使用Include(扩展方法)。由于延期执行的优势,您的查询将会触发一次,您将得到您想要的任何内容。 –

+0

哦,是的,让我编辑代码。我正在测试它与一个子表 – Farax

+2

你必须使用像这样新的QuestionsRepository()。GetAll()。Include(“Answers”)。ToList() –

回答

3

在getAll方法中,您必须返回DbSet并调用该方法。您必须使用Include(extenstion方法)。由于利用延迟执行的查询会触发一次,你会得到任何你想要的..

,你必须使用类似这样

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

new QuestionsRepository().GetAll().Include(x => x.Answers).ToList(); 
在GETALL方法