创建一个通用方法,其中表达式可以作为参数传递以进行动态查询

时间:2011-10-14 11:17:35

标签: linq entity-framework entity-framework-4 repository

我正在使用EF。和存储库模式。

具体问题是我如何编写下面的GetPositionByCustomExpression,以便从调用者传递一个表达式,有时表达式可能包含一个过滤器,或者2,甚至表达式可能包含一个订单?

     public interface IPositionRepository
        {
            void CreateNewPosition(Position contactToCreate);
            void DeletePosition(int id);
            Position GetPositionByID(int id);
            IEnumerable<Position> GetAllPositions();
            int SaveChanges();
            IEnumerable<Position> GetPositionByCustomExpression();  //---> What to put here??
        }


public class PositionRepository : IPositionRepository
    {

        private HRContext _db = new HRContext();

        public Position GetPositionByID(int id)
        {
            return _db.Positions.FirstOrDefault(d => d.PositionID == id);
        }

        public IEnumerable<Position> GetAllPosition()
        {
            return _db.Positions.ToList();
        }

        public void CreateNewContact(Position positionToCreate)
        {
            _db.Positions.Add(positionToCreate);
            _db.SaveChanges();
        }

        public int SaveChanges()
        {
            return _db.SaveChanges();
        }

        public void DeletePosition(int id)
        {
            var posToDel = GetPositionByID(id);
            _db.Positions.Remove(posToDel);
            _db.SaveChanges();
        }

        /// <summary>
        /// Lets suppose we have a field called name, another years of experience, and another department.
        /// How can I create a generic way in ONE simple method to allow the caller of this method to pass
        /// 1, 2 or 3 parameters.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Position> GetPositionByCustomExpression()   // --> What to put here?
        {
            _db.Positions.Find(); // ---> and here??

        }

1 个答案:

答案 0 :(得分:1)

您可以将Expression<Func<Position, bool>>类型参数带到方法

public interface IPositionRepository
    {
        //others
        IEnumerable<Position> GetPositionByCustomExpression(Expression<Func<Position, bool>> predicate);
    }

public class PositionRepository : IPositionRepository
{

    public IEnumerable<Position> GetPositionByCustomExpression(Expression<Func<Position, bool>> predicate)
    {
        _db.Positions.Where(predicate);

    }
 }

然后您可以使用谓词

var positions = repository
.GetPositionByCustomExpression(p => p.Name.StartsWith("Foo") && p.BasicSalary > 100000)