Skip to content

Creating Basic Database Queries

StrutTower edited this page Jul 4, 2024 · 2 revisions

Creating a query for a single column

public class PersonRepository : DbRepository<Person> {

    public PersonRepository(UnitOfWork uow) : base(uow.DbAdapter) { }

    // Returns a single entity with a matching ID
    public Person GetByID(int id) {
        return GetSingleEntity(WhereEqual(x => x.ID, id));
    }

    // Returns all entities with IsActive equal to true
    public List<Person> GetActive() {
        return GetEntities(WhereEqual(x => x.IsActive, true));
    }

    // Returns all entities with a CreatedOn date before the supplied DateTime
    public List<Person> GetCreatedBefore(DateTime datetime) {
        return GetEntities(Where(x => x.CreatedOn, Comparison.LessThan, datetime));
    }

    // Return all entities that contain the supplied string in the DisplayName field
    public List<Person> SearchDisplayName(string q) {
        return GetEntities(Where(x => x.DisplayName, Comparison.LikeBothSidesWildcard, q));
    }
}

Creating a query for multiple columns

public class PersonRepository : DbRepository<Person> {

    public PersonRepository(UnitOfWork uow) : base(uow.DbAdapter) { }

        // Returns all active entities with a display name
    public List<Person> GetActiveWithDisplayName() {
        return GetEntities(Query
            .WhereEqual(x => x.IsActive, true)
            .Where(x => x.DisplayName, Comparison.NotEquals, null));
    }

    // Return all entities that contain the supplied string in the DisplayName field.
    // Limit and offset the results by the supplied numbers.
    public List<Person> SearchDisplayName(string q, int limit, int offset) {
        return GetEntities(Query
            .Where(x => x.DisplayName, Comparison.LikeBothSidesWildcard, q)
            .LimitTo(limit)
            .OffsetBy(offset));
    }

    // Returns all entities created between the two dates and sort by a descending order based on CreatedOn
    public List<Person> GetCreatedBetweenDates(DateTime start, DateTime end) {
        return GetEntities(Query
            .Where(x => x.CreatedOn, Comparison.GreaterThan, start)
            .Where(x => x.CreatedOn, Comparison.LessThanOrEqual, end)
            .OrderByDescending(x => x.CreatedOn));
    }## 
}