Example #1
0
    /// <summary>
    /// Note that this method will also set the correct Id in the contact itself
    /// </summary>
    public int Create(ContactModel contact)
    {
        CheckOperationAllowed(contact);

        using (IDbConnection con = SqliteHelper.CreateConnection())
        {
            using (IDbCommand cmd = con.CreateCommand())
            {
                #region Create the command text & parameters dynamically
                List <FieldInfo> allFields = contact.GetAllFields();
                StringBuilder    cmdText   = new StringBuilder("INSERT INTO Contact VALUES(@pId, ");
                allFields.ForEach(f =>
                {
                    cmdText.Append(string.Format("@p{0}, ", f.Name));
                    cmd.Parameters.Add(new SqliteParameter(string.Format("@p{0}", f.Name), f.GetValue(contact)));
                });
                cmdText.Length -= 2; // Remove the last ", "
                cmdText.Append(")");
                cmd.CommandText = cmdText.ToString();
                #endregion
                cmd.Parameters.Add(new SqliteParameter("@pId", null));
                SqliteHelper.ExecuteNonQuery(con, cmd);
            }

            using (IDbCommand cmd = con.CreateCommand())
            {
                con.Open();
                cmd.CommandText = "SELECT Id FROM Contact ORDER BY Id DESC LIMIT 1";
                int id = Convert.ToInt32(cmd.ExecuteScalar());
                contact.SetId(id);
                return(id);
            }
        }
    }
Example #2
0
    public void Update(ContactModel contact)
    {
        CheckOperationAllowed(contact);

        using (IDbConnection con = SqliteHelper.CreateConnection())
            using (IDbCommand cmd = con.CreateCommand())
            {
                List <FieldInfo> allFields = contact.GetAllFields();
                #region Create the command text & parameters dynamically
                StringBuilder cmdText = new StringBuilder("UPDATE Contact SET ");
                allFields.ForEach(f =>
                {
                    cmdText.Append(string.Format("{0}=@p{0}, ", f.Name));
                    cmd.Parameters.Add(new SqliteParameter(string.Format("@p{0}", f.Name), f.GetValue(contact)));
                });
                cmdText.Length -= 2; // Remove the last ", "
                cmdText.Append(" WHERE ID=@pId AND Owner=@pOwner");
                cmd.CommandText = cmdText.ToString();
                cmd.Parameters.Add(new SqliteParameter("@pId", contact.Id));
                #endregion
                SqliteHelper.ExecuteNonQuery(con, cmd);
            }
    }