示例#1
0
 public SuperheroQuery(IEntityAdapter <Power> powerAdapter)
 {
     Field <ListGraphType <PowerType> >(
         "powers",
         resolve: context => powerAdapter.ReadAll()
         );
 }
示例#2
0
        public IEnumerable <Hero> ReadAll()
        {
            var heroes = new List <Hero>();

            using (var connection = new SqlConnection(ConnectionString))
            {
                var heroQueryString = "SELECT Id, Name, Location FROM Heroes";
                var heroCommand     = new SqlCommand(heroQueryString, connection);

                connection.Open();

                using (var reader = heroCommand.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        heroes.Add(new Hero((Guid)reader["Id"], (string)reader["Name"], (string)reader["Location"], new List <Power>()));
                    }
                }

                // TODO n + 1 query problem, kind of; is there a way to avoid this?
                // actually, O(|Heroes| * |Powers|)
                foreach (var hero in heroes)
                {
                    var allPowers = PowerAdapter.ReadAll();
                    foreach (var power in allPowers)
                    {
                        var associationQueryString = "SELECT * FROM HeroesPowersAssociation WHERE HeroId = @heroid AND PowerId = @powerid";
                        var associationCommand     = new SqlCommand(associationQueryString, connection);
                        associationCommand.Parameters.AddWithValue("@heroid", hero.Id);
                        associationCommand.Parameters.AddWithValue("@powerid", power.Id);

                        using (var reader = associationCommand.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                hero.Powers.Append(power);
                            }
                        }
                    }
                }
            }

            return(heroes);
        }