public static MailTagData ToTagData(this MailTag tag)
 {
     return(new MailTagData
     {
         Id = tag.Id,
         Name = tag.Name,
         Style = tag.Style,
         Addresses = new MailTagData.AddressesList <string>(tag.Addresses),
         LettersCount = tag.LettersCount
     });
 }
        public MailTag SaveMailTag(int id_tenant, string id_user, MailTag tag)
        {
            using (var db = GetDb()) 
            {
                using (var tx = db.BeginTransaction())
                {
                    if (tag.Id == 0)
                    {
                        tag.Id = db.ExecuteScalar<int>(
                            new SqlInsert(MAIL_TAG)
                                .InColumnValue(TagFields.id, 0)
                                .InColumnValue(TagFields.id_tenant, id_tenant)
                                .InColumnValue(TagFields.id_user, id_user)
                                .InColumnValue(TagFields.name, tag.Name)
                                .InColumnValue(TagFields.style, tag.Style)
                                .InColumnValue(TagFields.addresses, string.Join(";", tag.Addresses.ToArray()))
                                .Identity(0, 0, true));
                    }
                    else
                    {
                        db.ExecuteNonQuery(
                            new SqlUpdate(MAIL_TAG)
                                .Set(TagFields.name, tag.Name)
                                .Set(TagFields.style, tag.Style)
                                .Set(TagFields.addresses, string.Join(";", tag.Addresses.ToArray()))
                                .Where(TagFields.id, tag.Id));

                        db.ExecuteNonQuery(
                                new SqlDelete(MAIL_TAG_ADDRESSES)
                                    .Where(TagAddressFields.id_tag, tag.Id));
                    }

                    if (tag.Addresses.Any())
                    {
                        var insert_query =
                            new SqlInsert(MAIL_TAG_ADDRESSES)
                                .InColumns(TagAddressFields.id_tag,
                                           TagAddressFields.address,
                                           TagAddressFields.id_tenant);

                        tag.Addresses
                           .ForEach(addr =>
                                    insert_query
                                        .Values(tag.Id, addr, id_tenant));

                        db.ExecuteNonQuery(insert_query);
                    }

                    tx.Commit();
                }
            }

            return tag;
        }