Crusel
Crusel

Reputation: 13

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.

Upvotes: 0

Views: 253

Answers (1)

Izzy
Izzy

Reputation: 6866

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

Upvotes: 2

Related Questions