//TODO to be tested with composite pk and with Non-Identity PK --- And in general
        //TODO see if it's ok to not specify the db type and only the ouput direction
        /// <summary>
        /// Insert template
        /// </summary>
        /// <returns></returns>
        private string PrintInsertMethod()
        {
            var paramName = FirstCharacterToLower(_entityClassName);

            //Exclude de PK identity field to put "Direction Output" in Dapper params
            bool isOneColumnIdentity = _pkColumns.Count() == 1 && TSqlModelHelper.IsColumnIdentity(_pkColumns.ToList()[0]);
            var  normalColumns       = isOneColumnIdentity ? _allColumns.Except(_pkColumns) : _allColumns;

            string returnType = isOneColumnIdentity
                ? TSqlModelHelper.GetDotNetDataType(TSqlModelHelper.GetColumnSqlDataType(_pkColumns.ToArray()[0]))
                : "bool"; // return bool if insert ok  => we cannot return the new Id generated by Identity

            //If the PK is one identity field + one another field, we are f...
            string returnStatement = (returnType == "bool")
                ? "return true;"
                : $@"return p.Get<{returnType}> (""@{_pkColumns.ToArray()[0].Name.Parts[2]}"");";

            string spPkParams = isOneColumnIdentity
                ? String.Join(Environment.NewLine + "            ",
                              _pkColumns.Select(col =>
            {
                var colName = col.Name.Parts[2];
                return($@"p.Add(""@{colName}"", dbType:{TSqlModelHelper.GetDotNetDataType_SystemDataDbTypes(TSqlModelHelper.GetColumnSqlDataType(col,false))}, direction: ParameterDirection.Output);");
            }))
                : string.Empty; // no identity PK

            //Excluded columns in the SP
            var tmpColumns = TableSettings.SqlInsertSettings.FieldNamesExcluded != null
                ? normalColumns.Where(c => !TableSettings.SqlInsertSettings.FieldNamesExcluded.Split(',').Contains(c.Name.Parts[2]))
                : normalColumns;

            string spNormalParams = String.Join(Environment.NewLine + "            ",
                                                tmpColumns.Select(col =>
            {
                var colName    = col.Name.Parts[2];
                var entityProp = TSqlModelHelper.PascalCase(colName);
                return($@"p.Add(""@{colName}"", {paramName}.{entityProp});");
            }));



            string output = $@"
        /// <summary>
        /// Insert
        /// </summary>
        public async  Task<{returnType}> Insert({_entityClassFullName} {paramName})
        {{
            var p = new DynamicParameters();
            {spPkParams}
            {spNormalParams}

            _ = await _dbContext.Connection.ExecuteAsync
                (""usp{_entityClassName}_insert"", p, commandType: CommandType.StoredProcedure, transaction: _dbContext.Transaction);
            
            {returnStatement}
        }}";

            return(output);
        }
        /// <summary>
        /// Concat all the uk fields with their types (for method signature)
        /// </summary>
        /// <param name="ukColumns"></param>
        /// <returns></returns>
        private string ConcatUkFieldsWithTypes(IEnumerable <TSqlObject> ukColumns)
        {
            return(String.Join(", ",
                               ukColumns.Select(col =>
            {
                var colName = col.Name.Parts[2];
                var colDataType = col.GetColumnSqlDataType(false);

                //Search for custom member type or use the conversion from Sql Types
                var memberType = (TableSettings.CsEntitySettings.FieldNameCustomTypes != null &&
                                  TableSettings.CsEntitySettings.FieldNameCustomTypes.ContainsKey(colName)
                                        ? TableSettings.CsEntitySettings?.FieldNameCustomTypes[colName]
                                        : TSqlModelHelper.GetDotNetDataType(colDataType, false));

                return $"{memberType} {FirstCharacterToLower(TSqlModelHelper.PascalCase(colName))}";
            })
                               ));
        }
Exemplo n.º 3
0
        /// <summary>
        /// If composite pk, need to define a custom type for select by PKList
        /// </summary>
        /// <returns></returns>
        private string PrintPkType()
        {
            if (!TableSettings.GenerateSelectByPkList)
            {
                return(string.Empty);
            }

            var memberDeclarations = String.Join(Environment.NewLine + "        ", TSqlModelHelper.GetPrimaryKeyColumns(Table).Select(col =>
            {
                var colName     = col.Name.Parts[2];
                var memberName  = TSqlModelHelper.PascalCase(col.Name.Parts[2]);
                var colDataType = col.GetColumnSqlDataType(false);


                //Search for custom member type or use the conversion from Sql Types
                var hasCustomMemberType = _settings?.FieldNameCustomTypes?.ContainsKey(colName) ?? false;

                var memberType = hasCustomMemberType ? _settings.FieldNameCustomTypes[colName]
                    : TSqlModelHelper.GetDotNetDataType(colDataType);


                return($"public {memberType} {memberName} {{ get; set; }}");
            }));

            return
                ($@"
/// =================================================================
/// Author: {GeneratorSettings.AuthorName}
/// Description: PK class for the table {Table.Name} 
/// It's bit heavy (a lot of useless types in the DB) but you can
/// use get by PKList even if your pk is a composite one...
/// =================================================================
    public class {TSqlModelHelper.PascalCase(Table.Name.Parts[1])}_PK
    {{ 
        
        {memberDeclarations}

    }}");
        }
Exemplo n.º 4
0
        public override string Generate()
        {
            if (!TableSettings.GenerateEntities && !PreviewMode)
            {
                return(string.Empty);
            }

            var allColumns = Table.GetAllColumns();
            var pkColumns  = TSqlModelHelper.GetPrimaryKeyColumns(Table);

            // ICloneable interface
            var iCloneableFuncStr = "public object Clone()" + Environment.NewLine +
                                    "        {" + Environment.NewLine +
                                    "           return this.MemberwiseClone();" + Environment.NewLine +
                                    "        }";

            var iCloneable       = _settings.ImplementICloneable ? " : System.ICloneable" : null;
            var iCloneableMethod = _settings.ImplementICloneable ? iCloneableFuncStr : null;

            // Custom interface names
            string interfaceNames = "";

            if (!string.IsNullOrEmpty(_settings.ImplementCustomInterfaceNames))
            {
                interfaceNames = (_settings.ImplementICloneable)
                    ? ", " + _settings.ImplementCustomInterfaceNames
                    : " : " + _settings.ImplementCustomInterfaceNames;
            }

            var memberDeclarations = String.Join(Environment.NewLine + "        ", allColumns.Select(col =>
            {
                var colName     = col.Name.Parts[2];
                var memberName  = TSqlModelHelper.PascalCase(col.Name.Parts[2]);
                var colDataType = col.GetColumnSqlDataType(false);
                var isNullable  = col.IsColumnNullable();
                bool isPk       = (pkColumns.SingleOrDefault(c => c.Name.Parts[2] == colName) != null) ? true : false;

                //Search for custom member type or use the conversion from Sql Types
                var hasCustomMemberType = _settings?.FieldNameCustomTypes?.ContainsKey(colName) ?? false;

                var memberType = hasCustomMemberType ? _settings.FieldNameCustomTypes[colName]
                    : TSqlModelHelper.GetDotNetDataType(colDataType, isNullable);

                //Decorators
                var decorators = "";

                //String length
                if (_settings.StandardStringLengthDecorator)
                {
                    if (memberType == "string")
                    {
                        var colLen = col.GetProperty <int>(Column.Length);
                        if (colLen > 0)
                        {
                            decorators += $"[System.ComponentModel.DataAnnotations.StringLength({colLen})]"
                                          + Environment.NewLine + "        ";
                        }
                    }
                }

                // TODO : I don't think the condition is correct, check this with fab
                //Required
                if (_settings.StandardRequiredDecorator)
                {
                    if (!isNullable && !isPk)
                    {
                        decorators += $"[System.ComponentModel.DataAnnotations.Required]"
                                      + Environment.NewLine + "        ";
                    }
                }

                //Json ignore
                if (_settings.StandardJsonIgnoreDecorator)
                {
                    var colFound = _settings.FieldNamesWithJsonIgnoreDecorator
                                   .Split(',').Any(c => c == colName);

                    if (colFound)
                    {
                        decorators += $"[Newtonsoft.Json.JsonIgnore]"
                                      + Environment.NewLine + "        ";
                    }
                }

                //Custom field decorator
                if (_settings.FieldNameCustomDecorators != null && _settings.FieldNameCustomDecorators.Count > 0)
                {
                    if (_settings.FieldNameCustomDecorators.TryGetValue(colName, out string customDecorator))
                    {
                        decorators += customDecorator
                                      + Environment.NewLine + "        ";
                    }
                }

                return($"{decorators}public {memberType} {memberName} {{ get; set; }}" + Environment.NewLine);
            }));

            string pkType = PrintPkType();
            string output =
                $@" 
namespace { _settings.Namespace } {{

{pkType}    

/// =================================================================
/// Author: {GeneratorSettings.AuthorName}
/// Description: Entity class for the table {Table.Name} 
/// =================================================================

    public class {TSqlModelHelper.PascalCase(Table.Name.Parts[1])}{iCloneable}{interfaceNames}
    {{ 
        
        {memberDeclarations}

        {iCloneableMethod}

    }}
}}

";

            return(output);
        }