将多个Include语句传递到存储库

将多个Include语句传递到存储库

本文介绍了将多个Include语句传递到存储库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出一种将包含语句的集合传递到我的存储库中的方法,这样我就可以让它包含特定的实体.以下是我的存储库中的一些示例代码.

I am trying to figure out a way to pass a collection of include statements into my repository so that I can have it include specific entities. Below is some sample code from my repository.

   public TEntity GetById(Guid id)
        {
            return id != Guid.Empty ? GetSet().Find(id) : null;
        }
   private IDbSet<TEntity> GetSet()
            {
                return _unitOfWork.CreateSet<TEntity>();
            }

GetByID方法调用GetSet以返回实体集.我在想,如果我能以某种方式传入实体集合以(通过表达式)将其包含为我的GetById的一部分,那么我就不必将GetSet公开给我的服务.所以,像这样:

The GetByID method calls the GetSet to return the entity set. I was thinking, if I could somehow pass in a collection of entities to include (via an expression) as part of my GetById, this way I wouldn't have to expose the GetSet to my services. So, something like this:

var实体= _repository.GetById(theId,e => {e.Prop1,e.Prop2,e.Prop3});

var entity = _repository.GetById(theId, e => {e.Prop1, e.Prop2, e.Prop3});

然后我可以将该表达式传递到我的GetSet方法中,并将其传递到一个include语句中.有想法吗?

I could then pass that expression into my GetSet method and pass it into an include statement. Thoughts?

推荐答案

我最近在代码中做了类似的事情.以下内容对您有用吗?

I have done something like this in my code recently. Would the following work for you?

public TEntity GetById(Guid id, params Expression<Func<TEntity, object>>[] includeProperties)
    {
        if (id == Guid.Empty) return null;

        var set = _unitOfWork.CreateSet<TEntity>();
        foreach(var includeProperty in includeProperties)
        {
             set.Include(includeProperty);
        }
        return set.First(i => i.Id == id);
    }

然后您会这样称呼它...

Then you would call it like this...

var entity = _repository.GetById(theId, e => e.Prop1, e=> e.Prop2, e=> e.Prop3);

我知道这并不完全符合您的模式,但是我认为您可以根据需要对其进行重构.

I know this doesn't exactly follow your pattern, but I think you could refactor it as required.

这篇关于将多个Include语句传递到存储库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 03:08