Search code examples
c#npoco

How can be dynamic this query of npoco


Instead of the adding search method to every class like this;

    public List<InvoiceDetail> SearchById(int Id)
    {
        return db.Query<InvoiceDetail>()
            .Where(x => x.Id == Id)
            .ToList();
    }

How to add a method to base class like this;

    public virtual List<T> SearchById(int Id)
    {
        return db.Query<T>()
           .Where(x => x.Id == Id)
           .ToList();
    }

"T does not contain a definition for Id"

Because Id is the definition of Detail entities.


Solution

  • You can achieve this by creating a base class as:

    public class BaseEntity
    {
        public int Id { get; set; }
    }
    

    Then make the appropriate entity classes inherit from BaseEntity as:

    public class Detail : BaseEntity
    {
       //some props for Detail class only
    }
    

    Now for your search method you can use the where T : class constrain as:

    public List<T> SearchById<T>(int id) where T : BaseEntity
    {
       return db.Query<T>()
           .Where(x => x.Id == Id)
           .ToList();
    }