我创建了一个通用存储库,可以为我的项目提供帮助.
I created a Generic Repository that can help me in my projects.
问题:
这些天,我从事一个项目,我想从一些相关的表中获取数据(一个表中的所有数据,并从我选择的其他表中加载所有相关的数据),即存储库创建我无法处理这个问题,我也不想直接使用Entity Framework Core.
In these days I work on a project and I want to get data from some related tables (all data from one table and also load all related data from other tables that I select), the repository I was created can't handle this also I don't want to work directly with Entity Framework Core.
我的存储库:
我的存储库是一个开源项目,您可以在此处查看源代码 .
My repository is an open source project, you can see the source code from here.
我想要的是什么
我的想法是在我的通用存储库中创建一个方法,该方法将接收我要从中选择数据的实体,并接收一个告诉其从气味实体中加载数据的表达式.和一些相关表(不是所有相关表,而是一些我将在表达式中发送的相关表).
My idea is to create a method in my generic repository, this method will receive the entity that I want to select data from, and receive an expression that told it to load data from the scent entity and some related tables (not all related table but some related table that I will send in the expression).
我该如何解决?
推荐答案它高度依赖于通用存储库的特定实现,但是以下代码可能会帮助您理解这一点-
It is highly dependent on your specific implementation of generic repository, but the following code might help you to get the idea -
public async Task<TEntity> LoadSingleWithRelatedAsync<TEntity>(TEntity entity, params Expression<Func<TEntity, object>>[] expressionList) where TEntity : EntityBase { if (entity == null) return null; var query = _DbCtx.Set<TEntity>().AsQueryable(); foreach (var expression in expressionList) { query = query.Include(expression); } return await query.FirstOrDefaultAsync(p => p.Id == entity.Id); }其中 EntityBase 是-
public class EntityBase { public int Id { get; set; } }以下是您如何使用它的示例-
Following is an example of how you would use it -
// Order has a Customer parent and a list of OrderLine children var loadedOrder = await _Repo.LoadSingleWithRelatedAsync(order, p => p.Customer, p => OrderLines);2021.04.01 如果要集合而不是单个实体,则该方法可能类似于-
2021.04.01 If you want a collection instead of a single entity, the method might look like -
public async Task<IEnumerable<TEntity>> LoadAllWithRelatedAsync<TEntity>(params Expression<Func<TEntity, object>>[] expressionList) where TEntity : class { var query = _DbCtx.Set<TEntity>().AsQueryable(); foreach (var expression in expressionList) { query = query.Include(expression); } return await query.ToListAsync(); }这里-
不需要更多推荐
EF Core:如何从通用存储库中的表和相关表加载数据
发布评论