How to use joins with generic repository pattern - Entity Framework

女生的网名这么多〃 提交于 2019-12-06 19:10:29

So based on your edit, I'm assuming you would like to join Students and Standards.

The first thing you have to do is change the repository so that it doesn't instantiate the context. You should pass that in as a parameter and store a reference to it:

public Repository(MyDbContext myCtx)
{
    context = myCtx;
    this.dbSet = context.Set<T>();
}

The second thing you have to do is change your repository to change the GetAll() method to return IQueryable<T> instead of ICollection<T>.

Then change the implementation of GetAll():

return dbSet;

This way you only get back a query and not the evaluated list of all the entities. And then you can do the join with the GetAll() method of the repositories just like you would do it with the db sets:

using (MyDbContext ctx = new MyDbContext())
{
  var studentRep = new Repository<Student>(ctx);
  var standardRep = new Repository<Standard>(ctx);
  var studentToStandard = studentRep.GetAll().Join(standardRep.GetAll(), 
                        student => student.StandardRefId,
                        standard => standard.StandardId,
                        (stud, stand) => new { Student=stud, Standard=stand }).ToList();
}

With this you get an IQueryable<T> in studentToStandard, which will run in the database once you call ToList() on it. Note that you have to pass in the same context to both of the repositories in order for this to work.

I recommend that you check out the Unit Of Work design pattern as well. It helps a lot when dealing with multiple repositories.

https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

This is a more structured and better maintainable way of handling transactions when it comes to multiple entity sets, and promotes better separation of concerns.

Hope I understood your problem correctly and this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!