Exemplo n.º 1
0
        /// <summary>
        /// Inserts a new Entity into the database, and sets any Foreign key properties. If the
        /// entity table has a single integer primary key, the primary key value will be updated
        /// with the <see cref="SQLiteConnection.LastInsertRowId"/>.
        /// </summary>
        /// <remarks>This method utilizes the <see cref="PreparedNonQuery"/> to speed things along.</remarks>
        /// <param name="obj">The <see cref="TEntity"/> object to add to the dataset</param>
        public void Add(TEntity obj)
        {
            // For fetching the RowID
            AttributeInfo rowid = EntityTable.RowIdColumn;

            // Generate the SQL
            if (InsertQuery == null)
            {
                using (var query = new InsertQueryBuilder(EntityTable.TableName, Context))
                {
                    foreach (var attribute in EntityTable.Columns)
                    {
                        // Grab value
                        PropertyInfo property = attribute.Value.Property;
                        bool         isKey    = attribute.Value.PrimaryKey;

                        // Check for integer primary keys
                        if (isKey && EntityTable.HasRowIdAlias && EntityTable.RowIdColumn == attribute.Value)
                        {
                            continue;
                        }

                        // Add attribute to the field list
                        query.Set(attribute.Key, new SqlLiteral($"@{attribute.Key}"));
                    }

                    InsertQuery = new PreparedNonQuery(query.BuildCommand());
                }
            }

            // Execute the SQL Command
            lock (InsertQuery)
            {
                InsertQuery.SetParameters(obj, EntityTable);
                int result = InsertQuery.Execute();


                // If the insert was successful, lets build our Entity relationships
                if (result > 0)
                {
                    // If we have a Primary key that is determined database side,
                    // than we can update the current object's key value here
                    if (EntityTable.HasRowIdAlias)
                    {
                        long rowId = Context.Connection.LastInsertRowId;
                        rowid.Property.SetValue(obj, Convert.ChangeType(rowId, rowid.Property.PropertyType));
                    }

                    // Build relationships after a fresh insert
                    EntityTable.CreateRelationships(obj, Context);
                }
            }
        }