Esempio n. 1
0
        /// <summary>
        /// Lazy loads the child entities of a foreign key constraint
        /// </summary>
        public IEnumerator <TChildEntity> GetEnumerator()
        {
            // Grab table mappings
            TableMapping parentTable = EntityCache.GetTableMap(typeof(TParentEntity));
            TableMapping childTable  = EntityCache.GetTableMap(typeof(TChildEntity));

            // Create the SQL Command
            using (SQLiteContext context = new SQLiteContext(ConnectionString))
            {
                // Open the connection
                context.Connect();

                // Begin a new Select Query
                SelectQueryBuilder query = new SelectQueryBuilder(context);
                query.From(childTable.TableName).SelectAll();

                // Grab the foreign key constraints
                var fkinfos = childTable.ForeignKeys.Where(x => x.ParentEntityType == parentTable.EntityType);
                foreach (ForeignKeyConstraint fkinfo in fkinfos)
                {
                    // Append each key => value to the query
                    for (int i = 0; i < fkinfo.ForeignKey.Attributes.Length; i++)
                    {
                        string attrName      = fkinfo.ForeignKey.Attributes[i];
                        string parentColName = fkinfo.InverseKey.Attributes[i];

                        // Add column expression
                        AttributeInfo attribute = parentTable.GetAttribute(parentColName);
                        query.Where(attrName, Comparison.Equals, attribute.Property.GetValue(Entity));
                    }

                    // Create a new clause, to seperate by an OR
                    query.WhereStatement.CreateNewClause();
                }

                // Create command
                using (SQLiteCommand command = query.BuildCommand())
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        // If we have rows, return each row
                        while (reader.Read())
                        {
                            yield return(context.ConvertToEntity <TChildEntity>(childTable, reader));
                        }

                        // Cleanup
                        reader.Close();
                    }
            }
        }