开发者

Create a generic method where a expression can be passed as parameter to make dynamic queries

开发者 https://www.devze.com 2023-04-13 04:31 出处:网络
I am using EF. and the repository Pattern. The specific question is how can I write the GetPositionByCustomExpression below so that from the caller I can pass an expression, sometimes the expression

I am using EF. and the repository Pattern.

The specific question is how can I write the GetPositionByCustomExpression below so that from the caller I can pass an expression, sometimes the expression could contain one filter, or 2, or even the expression could contain an order?

     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.Posit开发者_开发知识库ions.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??

        }


You can take a Expression<Func<Position, bool>> type parameter to the method

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);

    }
 }

Then you can use predicates as follows

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

精彩评论

暂无评论...
验证码 换一张
取 消