예제 #1
0
        public IEnumerable <IPersonEntity> ListPeople(IPeopleFilter filter)
        {
            var people = new List <IPersonEntity>();

            // For most databases this would be call to a Stored Procedure (or a View) with the SPROC handling the filtering
            // and the age group.
            // But here - particularly since we're allowing unfiltered lists - just do a simple
            // SELECT * and do the filtering with LINQ.
            var sql = " SELECT * FROM Person ";
            var dt  = ExecuteQuery(sql);

            // Q: How would this happen without an exception?
            // A: Someone changed the ExecuteQuery method
            if (dt == null)
            {
                throw new Exception($"An empty dataset was returned from the query: {sql}");
            }

            foreach (DataRow row in dt.Rows)
            {
                var person = new PersonEntity();

                person.ID        = (int)((Int64)row["ID"]);
                person.FirstName = row["FirstName"].ToString();
                person.LastName  = row["LastName"].ToString();
                person.Age       = (int)((Int64)row["Age"]);

                person.AgeRange = _agegroup.Get(person.Age);

                people.Add(person);
            }

            if (filter != null)
            {
                people = people.Where(p => (filter.FirstName == null || p.FirstName.StartsWith(filter.FirstName, StringComparison.CurrentCultureIgnoreCase)) &&
                                      (filter.LastName == null || p.LastName.StartsWith(filter.LastName, StringComparison.CurrentCultureIgnoreCase)) &&
                                      (filter.MinAge == null || filter.MinAge <= p.Age) &&
                                      (filter.MaxAge == null || filter.MaxAge > p.Age)).ToList();
            }


            return(people);
        }