sqlserver CodeFirst DbFirst 测试通过

This commit is contained in:
28810 2018-12-19 15:17:44 +08:00
parent 751b240533
commit d619d29cfa
22 changed files with 1336 additions and 332 deletions

View File

@ -1,126 +1 @@
 
//using System;
//using System.Collections;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Text.RegularExpressions;
//using FreeSql;
//using FreeSql.DatabaseModel;
////namespace TplDynamicCodeGenerate {
//public class TplDynamicCodeGenerate_view1 : FreeSql.Generator.TemplateEngin.ITemplateOutput {
// public FreeSql.Generator.TemplateEngin.TemplateReturnInfo OuTpUt(StringBuilder tOuTpUt, IDictionary oPtIoNs, string rEfErErFiLeNaMe, FreeSql.Generator.TemplateEngin tEmPlAtEsEnDeR) {
// FreeSql.Generator.TemplateEngin.TemplateReturnInfo rTn = tOuTpUt == null ?
// new FreeSql.Generator.TemplateEngin.TemplateReturnInfo { Sb = (tOuTpUt = new StringBuilder()), Blocks = new Dictionary<string, int[]>() } :
// new FreeSql.Generator.TemplateEngin.TemplateReturnInfo { Sb = tOuTpUt, Blocks = new Dictionary<string, int[]>() };
// Dictionary<string, int[]> TPL__blocks = rTn.Blocks;
// Stack<int[]> TPL__blocks_stack = new Stack<int[]>();
// int[] TPL__blocks_stack_peek;
// List<IDictionary> TPL__forc = new List<IDictionary>();
// Func<IDictionary> pRoCeSsOpTiOnS = new Func<IDictionary>(delegate () {
// IDictionary nEwoPtIoNs = new Hashtable();
// foreach (DictionaryEntry oPtIoNs_dE in oPtIoNs)
// nEwoPtIoNs[oPtIoNs_dE.Key] = oPtIoNs_dE.Value;
// foreach (IDictionary TPL__forc_dIc in TPL__forc)
// foreach (DictionaryEntry TPL__forc_dIc_dE in TPL__forc_dIc)
// nEwoPtIoNs[TPL__forc_dIc_dE.Key] = TPL__forc_dIc_dE.Value;
// return nEwoPtIoNs;
// });
// FreeSql.Generator.TemplateEngin.TemplateIf tPlIf = delegate (object exp) {
// if (exp is bool) return (bool)exp;
// if (exp == null) return false;
// if (exp is int && (int)exp == 0) return false;
// if (exp is string && (string)exp == string.Empty) return false;
// if (exp is long && (long)exp == 0) return false;
// if (exp is short && (short)exp == 0) return false;
// if (exp is byte && (byte)exp == 0) return false;
// if (exp is double && (double)exp == 0) return false;
// if (exp is float && (float)exp == 0) return false;
// if (exp is decimal && (decimal)exp == 0) return false;
// return true;
// };
// FreeSql.Generator.TemplateEngin.TemplatePrint print = delegate (object[] pArMs) {
// if (pArMs == null || pArMs.Length == 0) return;
// foreach (object pArMs_A in pArMs) if (pArMs_A != null) tOuTpUt.Append(pArMs_A);
// };
// FreeSql.Generator.TemplateEngin.TemplatePrint Print = prin
// dynamic index = oPtIoNs["index"];
// dynamic col = oPtIoNs["col"];
// dynamic table = oPtIoNs["table"];
// dynamic dbfirst = oPtIoNs["dbfirst"]; t;
// tOuTpUt.Append("using System;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Reflection;\r\nusing System.Threading.Tasks;\r\nusing Newtonsoft.Json;\r\nusing FreeSql.DataAnnotations;\r\n");
// var dbf = dbfirst as FreeSql.IDbFirst;
// var cols = (table.Columns as List<DbColumnInfo>);
// Func<string, string> UString = stra => stra.Substring(0, 1).ToUpper() + stra.Substring(1);
// Func<DbColumnInfo, string> GetCsType = cola3 => {
// if (cola3.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || cola3.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) {
// return $"{UString(cola3.Table.Name)}{cola3.Name.ToUpper()}{(cola3.IsNullable ? "?" : "")}";
// }
// return dbf.GetCsType(cola3);
// };
// tOuTpUt.Append("\r\nnamespace test.Model {\r\n\r\n [JsonObject(MemberSerialization.OptIn), Table(Name = \"");
// Print(!string.IsNullOrEmpty(table.Schema) ? table.Schema + "." : "");
// tOuTpUt.Append("");
// Print(table.Name);
// tOuTpUt.Append("\"");
// if (tPlIf(cols.Where(cola003 => cola003.Name.ToLower() == "is_deleted" || cola003.Name.ToLower() == "isdeleted").Any())) {
// tOuTpUt.Append(", SelectFilter = \"a.IsDeleted = 1\"");
// }
// tOuTpUt.Append(")]\r\n public partial class ");
// Print(UString(table.Name));
// tOuTpUt.Append(" {");
// //new Action(delegate () {
// IDictionary TPL__tmp1 = new Hashtable();
// TPL__forc.Add(TPL__tmp1);
// var TPL__tmp2 = table.Columns;
// var TPL__tmp3 = col;
// var TPL__tmp4 = index;
// index = 0;
// if (TPL__tmp2 != null)
// foreach (var TPL__tmp5 in TPL__tmp2) {
// TPL__tmp1["index"] = ++index;
// TPL__tmp1["col"] = TPL__tmp5;
// col = TPL__tmp5;
// tOuTpUt.Append("\r\n ");
// if (tPlIf(string.IsNullOrEmpty(col.Coment) == false)) {
// tOuTpUt.Append("/// <summary>\r\n /// ");
// Print(col.Coment.Replace("\r\n", "\n").Replace("\n", "\r\n /// "));
// tOuTpUt.Append("\r\n /// </summary>");
// }
// tOuTpUt.Append("\r\n [JsonProperty, Column(Name = \"");
// Print(col.Name);
// tOuTpUt.Append("\", DbType = \"");
// Print(col.DbTypeTextFull);
// tOuTpUt.Append("\"");
// if (tPlIf(col.IsPrimary == true)) {
// tOuTpUt.Append(", IsPrimary = true");
// }
// tOuTpUt.Append("");
// if (tPlIf(col.IsIdentity == true)) {
// tOuTpUt.Append(", IsIdentity = true");
// }
// tOuTpUt.Append("");
// if (tPlIf(col.IsNullable == true)) {
// tOuTpUt.Append(", IsNullable = true");
// }
// tOuTpUt.Append(")]\r\n public ");
// Print(GetCsType(col));
// tOuTpUt.Append(" ");
// Print(UString(col.Name));
// tOuTpUt.Append(" { get; set; }\r\n ");
// }
// col = TPL__tmp3;
// index = TPL__tmp4;
// TPL__forc.RemoveAt(TPL__forc.Count - 1);
// //})();
// tOuTpUt.Append("\r\n }\r\n");
// tEmPlAtEsEnDeR.RenderFile2(tOuTpUt, pRoCeSsOpTiOnS(), "../../include/enumtype.tpl", rEfErErFiLeNaMe);
// tOuTpUt.Append("\r\n}");
// return rTn;
// }
//}
////}

View File

@ -21,7 +21,7 @@ namespace FreeSql.Tests.Generator {
[Fact] [Fact]
public void BuildRichEntityNavigationObject() { public void BuildRichEntityNavigationObject() {
var gen = new TemplateGenerator(); var gen = new TemplateGenerator();
gen.Build(g.mysql.DbFirst, @"C:\Users\28810\Desktop\github\FreeSql\Templates\MySql\rich-entity-navigation-object", @"C:\Users\28810\Desktop\新建文件夹 (9)", "ManagerDB"); gen.Build(g.mysql.DbFirst, @"C:\Users\28810\Desktop\github\FreeSql\Templates\MySql\rich-entity-navigation-object", @"C:\Users\28810\Desktop\新建文件夹 (9)", "cccddd");
} }
} }
} }

View File

@ -0,0 +1,27 @@
using FreeSql.DataAnnotations;
using FreeSql.Generator;
using System;
using Xunit;
namespace FreeSql.Tests.Generator {
public class SqlServerTemplateGeneratorTest {
[Fact]
public void BuildSimpleEntity() {
var gen = new TemplateGenerator();
gen.Build(g.sqlserver.DbFirst, @"C:\Users\28810\Desktop\github\FreeSql\Templates\SqlServer\simple-entity", @"C:\Users\28810\Desktop\新建文件夹 (9)", "shop");
}
[Fact]
public void BuildSimpleEntityNavigationObject () {
var gen = new TemplateGenerator();
gen.Build(g.sqlserver.DbFirst, @"C:\Users\28810\Desktop\github\FreeSql\Templates\SqlServer\simple-entity-navigation-object", @"C:\Users\28810\Desktop\新建文件夹 (9)", "shop");
}
[Fact]
public void BuildRichEntityNavigationObject() {
var gen = new TemplateGenerator();
gen.Build(g.sqlserver.DbFirst, @"C:\Users\28810\Desktop\github\FreeSql\Templates\SqlServer\rich-entity-navigation-object", @"C:\Users\28810\Desktop\新建文件夹 (9)", "shop");
}
}
}

View File

@ -12,16 +12,174 @@ namespace FreeSql.Tests.SqlServer {
var sql = g.sqlserver.CodeFirst.GetComparisonDDLStatements<TableAllType>(); var sql = g.sqlserver.CodeFirst.GetComparisonDDLStatements<TableAllType>();
sql = g.sqlserver.CodeFirst.GetComparisonDDLStatements<Tb_alltype>();
} }
[JsonObject(MemberSerialization.OptIn), Table(Name = "dbo.tb_alltype")]
public partial class Tb_alltype {
[JsonProperty, Column(Name = "Id", DbType = "int", IsPrimary = true, IsIdentity = true)]
public int Id { get; set; }
[JsonProperty, Column(Name = "testFieldBool1111", DbType = "bit")]
public bool TestFieldBool1111 { get; set; }
[JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit", IsNullable = true)]
public bool? TestFieldBoolNullable { get; set; }
[JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint")]
public sbyte TestFieldByte { get; set; }
[JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint", IsNullable = true)]
public sbyte? TestFieldByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldBytes", DbType = "varbinary(255)", IsNullable = true)]
public byte[] TestFieldBytes { get; set; }
[JsonProperty, Column(Name = "testFieldDateTime", DbType = "datetime")]
public DateTime TestFieldDateTime { get; set; }
[JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)]
public DateTime? TestFieldDateTimeNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDateTimeNullableOffset", DbType = "datetimeoffset", IsNullable = true)]
public DateTime? TestFieldDateTimeNullableOffset { get; set; }
[JsonProperty, Column(Name = "testFieldDateTimeOffset", DbType = "datetimeoffset")]
public DateTime TestFieldDateTimeOffset { get; set; }
[JsonProperty, Column(Name = "testFieldDecimal", DbType = "decimal(10,2)")]
public decimal TestFieldDecimal { get; set; }
[JsonProperty, Column(Name = "testFieldDecimalNullable", DbType = "decimal(10,2)", IsNullable = true)]
public decimal? TestFieldDecimalNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDouble", DbType = "float")]
public double TestFieldDouble { get; set; }
[JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "float", IsNullable = true)]
public double? TestFieldDoubleNullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1", DbType = "int")]
public int TestFieldEnum1 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "int", IsNullable = true)]
public int? TestFieldEnum1Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2", DbType = "bigint")]
public long TestFieldEnum2 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "bigint", IsNullable = true)]
public long? TestFieldEnum2Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldFloat", DbType = "real")]
public float TestFieldFloat { get; set; }
[JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "real", IsNullable = true)]
public float? TestFieldFloatNullable { get; set; }
[JsonProperty, Column(Name = "testFieldGuid", DbType = "uniqueidentifier")]
public Guid TestFieldGuid { get; set; }
[JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "uniqueidentifier", IsNullable = true)]
public Guid? TestFieldGuidNullable { get; set; }
[JsonProperty, Column(Name = "testFieldInt", DbType = "int")]
public int TestFieldInt { get; set; }
[JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int", IsNullable = true)]
public int? TestFieldIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldLong", DbType = "bigint")]
public long TestFieldLong { get; set; }
[JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint")]
public sbyte TestFieldSByte { get; set; }
[JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint", IsNullable = true)]
public sbyte? TestFieldSByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldShort", DbType = "smallint")]
public short TestFieldShort { get; set; }
[JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint", IsNullable = true)]
public short? TestFieldShortNullable { get; set; }
[JsonProperty, Column(Name = "testFieldString", DbType = "nvarchar(255)", IsNullable = true)]
public string TestFieldString { get; set; }
[JsonProperty, Column(Name = "testFieldTimeSpan", DbType = "time")]
public TimeSpan TestFieldTimeSpan { get; set; }
[JsonProperty, Column(Name = "testFieldTimeSpanNullable", DbType = "time", IsNullable = true)]
public TimeSpan? TestFieldTimeSpanNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUInt", DbType = "int")]
public int TestFieldUInt { get; set; }
[JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int", IsNullable = true)]
public int? TestFieldUIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldULong", DbType = "bigint")]
public long TestFieldULong { get; set; }
[JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint", IsNullable = true)]
public long? TestFieldULongNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint")]
public short TestFieldUShort { get; set; }
[JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint", IsNullable = true)]
public short? TestFieldUShortNullable { get; set; }
[JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint", IsNullable = true)]
public long? TestFielLongNullable { get; set; }
}
[Table(Name = "tb_alltype")] [Table(Name = "tb_alltype")]
class TableAllType { class TableAllType {
[Column(IsIdentity = true, IsPrimary = true)] [Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; } public int Id { get; set; }
[Column(OldName = "testFieldBool1111")] [Column(Name = "testFieldBool1111")]
public bool testFieldBool { get; set; } public bool testFieldBool { get; set; }
public sbyte testFieldSByte { get; set; } public sbyte testFieldSByte { get; set; }
public short testFieldShort { get; set; } public short testFieldShort { get; set; }

View File

@ -0,0 +1,21 @@
using FreeSql.DataAnnotations;
using System;
using Xunit;
namespace FreeSql.Tests.SqlServer {
public class SqlServerDbFirstTest {
[Fact]
public void GetDatabases() {
var t1 = g.sqlserver.DbFirst.GetDatabases();
}
[Fact]
public void GetTablesByDatabase() {
var t2 = g.sqlserver.DbFirst.GetTablesByDatabase(g.sqlserver.DbFirst.GetDatabases()[0]);
}
}
}

View File

@ -34,6 +34,7 @@ namespace FreeSql.Generator {
if (fi.Name.StartsWith("for-table.")) { if (fi.Name.StartsWith("for-table.")) {
foreach (var table in tables) { foreach (var table in tables) {
var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "table", table }, { "dbfirst", dbfirst } }); var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "table", table }, { "dbfirst", dbfirst } });
if (result.EndsWith("return;")) continue;
var outputName = table.Name + outputExtension; var outputName = table.Name + outputExtension;
var mcls = Regex.Match(result, @"\s+class\s+(\w+)"); var mcls = Regex.Match(result, @"\s+class\s+(\w+)");
if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension; if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;

View File

@ -360,7 +360,7 @@ where a.constraint_schema in ({1}) and a.table_name in ({0}) and not isnull(posi
}); });
foreach(var loc4 in loc1) { foreach(var loc4 in loc1) {
var dicUniques = new Dictionary<string, List<DbColumnInfo>>(); var dicUniques = new Dictionary<string, List<DbColumnInfo>>();
dicUniques.Add(string.Join(",", loc4.Primarys.Select(a => a.Name)), loc4.Primarys); if (loc4.Primarys.Count > 0) dicUniques.Add(string.Join(",", loc4.Primarys.Select(a => a.Name)), loc4.Primarys);
foreach(var loc5 in loc4.Uniques) { foreach(var loc5 in loc4.Uniques) {
var dickey = string.Join(",", loc5.Select(a => a.Name)); var dickey = string.Join(",", loc5.Select(a => a.Name));
if (dicUniques.ContainsKey(dickey)) continue; if (dicUniques.ContainsKey(dickey)) continue;

View File

@ -359,7 +359,7 @@ where a.constraint_schema in ({1}) and a.table_name in ({0}) and not isnull(posi
}); });
foreach (var loc4 in loc1) { foreach (var loc4 in loc1) {
var dicUniques = new Dictionary<string, List<DbColumnInfo>>(); var dicUniques = new Dictionary<string, List<DbColumnInfo>>();
dicUniques.Add(string.Join(",", loc4.Primarys.Select(a => a.Name)), loc4.Primarys); if (loc4.Primarys.Count > 0) dicUniques.Add(string.Join(",", loc4.Primarys.Select(a => a.Name)), loc4.Primarys);
foreach (var loc5 in loc4.Uniques) { foreach (var loc5 in loc4.Uniques) {
var dickey = string.Join(",", loc5.Select(a => a.Name)); var dickey = string.Join(",", loc5.Select(a => a.Name));
if (dicUniques.ContainsKey(dickey)) continue; if (dicUniques.ContainsKey(dickey)) continue;

View File

@ -60,7 +60,6 @@ namespace FreeSql.SqlServer {
{ (int)SqlDbType.Int, ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, { (int)SqlDbType.Int, ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") },
{ (int)SqlDbType.BigInt, ("(long?)", "long.Parse({0})", "{0}.ToString()", "long?", typeof(long), typeof(long?), "{0}.Value", "GetInt64") }, { (int)SqlDbType.BigInt, ("(long?)", "long.Parse({0})", "{0}.ToString()", "long?", typeof(long), typeof(long?), "{0}.Value", "GetInt64") },
{ (int)SqlDbType.Decimal, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") },
{ (int)SqlDbType.SmallMoney, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, { (int)SqlDbType.SmallMoney, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") },
{ (int)SqlDbType.Money, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, { (int)SqlDbType.Money, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") },
{ (int)SqlDbType.Decimal, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, { (int)SqlDbType.Decimal, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") },
@ -86,7 +85,7 @@ namespace FreeSql.SqlServer {
{ (int)SqlDbType.NVarChar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, { (int)SqlDbType.NVarChar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") },
{ (int)SqlDbType.NText, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, { (int)SqlDbType.NText, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") },
{ (int)SqlDbType.UniqueIdentifier, ("(Guid?)", "Guid.Parse({0})", "{0}.ToString()", "MygisGeometry", typeof(Guid), typeof(Guid?), "{0}.Value", "GetGuid") }, { (int)SqlDbType.UniqueIdentifier, ("(Guid?)", "Guid.Parse({0})", "{0}.ToString()", "Guid?", typeof(Guid), typeof(Guid?), "{0}.Value", "GetGuid") },
}; };
public string GetCsConvert(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csConvert : trydc.csConvert.Replace("?", "")) : null; public string GetCsConvert(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csConvert : trydc.csConvert.Replace("?", "")) : null;
@ -104,11 +103,22 @@ namespace FreeSql.SqlServer {
} }
public List<DbTableInfo> GetTablesByDatabase(params string[] database) { public List<DbTableInfo> GetTablesByDatabase(params string[] database) {
List<DbTableInfo> loc1 = null; var olddatabase = "";
Dictionary<int, DbTableInfo> loc2 = new Dictionary<int, DbTableInfo>(); using (var conn = _orm.Ado.MasterPool.Get(TimeSpan.FromSeconds(5))) {
Dictionary<int, Dictionary<string, DbColumnInfo>> loc3 = new Dictionary<int, Dictionary<string, DbColumnInfo>>(); olddatabase = conn.Value.Database;
}
var dbs = database?.ToArray() ?? new[] { olddatabase };
var tables = new List<DbTableInfo>();
var sql = @" foreach (var db in dbs) {
if (string.IsNullOrEmpty(db)) continue;
var loc1 = new List<DbTableInfo>();
var loc2 = new Dictionary<int, DbTableInfo>();
var loc3 = new Dictionary<int, Dictionary<string, DbColumnInfo>>();
var sql = $@"
use {db};
select select
a.Object_id a.Object_id
,b.name 'Owner' ,b.name 'Owner'
@ -135,6 +145,8 @@ from sys.procedures a
inner join sys.schemas b on b.schema_id = a.schema_id inner join sys.schemas b on b.schema_id = a.schema_id
where a.type = 'P' and charindex('$NPSP', a.name) = 0 and charindex('diagram', a.name) = 0 where a.type = 'P' and charindex('$NPSP', a.name) = 0 and charindex('diagram', a.name) = 0
order by type desc, b.name, a.name order by type desc, b.name, a.name
;
use {olddatabase};
"; ";
var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
if (ds == null) return loc1; if (ds == null) return loc1;
@ -163,6 +175,7 @@ order by type desc, b.name, a.name
var loc88 = string.Join(",", loc66.Select(a => string.Concat(a))); var loc88 = string.Join(",", loc66.Select(a => string.Concat(a)));
var tsql_place = @" var tsql_place = @"
select select
isnull(e.name,'') + '.' + isnull(d.name,'') isnull(e.name,'') + '.' + isnull(d.name,'')
,a.Object_id ,a.Object_id
@ -200,6 +213,7 @@ from sys.columns", loc8);
,a.is_output 'IsIdentity' ,a.is_output 'IsIdentity'
from sys.parameters", loc88); from sys.parameters", loc88);
} }
sql = $"use {db};{sql};use {olddatabase}; ";
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
if (ds == null) return loc1; if (ds == null) return loc1;
@ -230,7 +244,8 @@ from sys.parameters", loc88);
loc3[object_id][column].CsType = this.GetCsTypeInfo(loc3[object_id][column]); loc3[object_id][column].CsType = this.GetCsTypeInfo(loc3[object_id][column]);
} }
sql = string.Format(@" sql = $@"
use {db};
select select
a.object_id 'Object_id' a.object_id 'Object_id'
,c.name 'Column' ,c.name 'Column'
@ -242,8 +257,10 @@ select
from sys.index_columns a from sys.index_columns a
inner join sys.indexes b on b.object_id = a.object_id and b.index_id = a.index_id inner join sys.indexes b on b.object_id = a.object_id and b.index_id = a.index_id
left join sys.columns c on c.object_id = a.object_id and c.column_id = a.column_id left join sys.columns c on c.object_id = a.object_id and c.column_id = a.column_id
where a.object_id in ({0}) where a.object_id in ({loc8})
", loc8); ;
use {olddatabase};
";
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
if (ds == null) return loc1; if (ds == null) return loc1;
@ -288,7 +305,7 @@ where a.object_id in ({0})
} }
} }
sql = string.Format(@" sql = $@"
select select
b.object_id 'Object_id' b.object_id 'Object_id'
,c.name 'Column' ,c.name 'Column'
@ -302,8 +319,10 @@ from sys.foreign_key_columns a
inner join sys.tables b on b.object_id = a.parent_object_id inner join sys.tables b on b.object_id = a.parent_object_id
inner join sys.columns c on c.object_id = a.parent_object_id and c.column_id = a.parent_column_id inner join sys.columns c on c.object_id = a.parent_object_id and c.column_id = a.parent_column_id
inner join sys.columns d on d.object_id = a.referenced_object_id and d.column_id = a.referenced_column_id inner join sys.columns d on d.object_id = a.referenced_object_id and d.column_id = a.referenced_column_id
where b.object_id in ({0}) where b.object_id in ({loc8})
", loc8); ;
use {olddatabase};
";
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
if (ds == null) return loc1; if (ds == null) return loc1;
@ -334,7 +353,7 @@ where b.object_id in ({0})
if (!fkColumns.TryGetValue(object_id, out loc12)) if (!fkColumns.TryGetValue(object_id, out loc12))
fkColumns.Add(object_id, loc12 = new Dictionary<int, DbForeignInfo>()); fkColumns.Add(object_id, loc12 = new Dictionary<int, DbForeignInfo>());
if (!loc12.TryGetValue(fk_id, out loc13)) if (!loc12.TryGetValue(fk_id, out loc13))
loc12.Add(fk_id, new DbForeignInfo { Table = loc2[object_id], ReferencedTable = loc10 }); loc12.Add(fk_id, loc13 = new DbForeignInfo { Table = loc2[object_id], ReferencedTable = loc10 });
loc13.Columns.Add(loc9); loc13.Columns.Add(loc9);
loc13.ReferencedColumns.Add(loc11); loc13.ReferencedColumns.Add(loc11);
} }
@ -376,7 +395,7 @@ where b.object_id in ({0})
}); });
foreach (var loc4 in loc1) { foreach (var loc4 in loc1) {
var dicUniques = new Dictionary<string, List<DbColumnInfo>>(); var dicUniques = new Dictionary<string, List<DbColumnInfo>>();
dicUniques.Add(string.Join(",", loc4.Primarys.Select(a => a.Name)), loc4.Primarys); if (loc4.Primarys.Count > 0) dicUniques.Add(string.Join(",", loc4.Primarys.Select(a => a.Name)), loc4.Primarys);
foreach (var loc5 in loc4.Uniques) { foreach (var loc5 in loc4.Uniques) {
var dickey = string.Join(",", loc5.Select(a => a.Name)); var dickey = string.Join(",", loc5.Select(a => a.Name));
if (dicUniques.ContainsKey(dickey)) continue; if (dicUniques.ContainsKey(dickey)) continue;
@ -387,7 +406,9 @@ where b.object_id in ({0})
loc2.Clear(); loc2.Clear();
loc3.Clear(); loc3.Clear();
return loc1; tables.AddRange(loc1);
}
return tables;
} }
} }
} }

View File

@ -57,8 +57,8 @@ namespace test.Model {
{/if}{/for}{for fk in fks} {/if}{/for}{for fk in fks}
public {#UString(fk.ReferencedTable.Name)} {#GetFkObjectName(fk)} { get; set; } public {#UString(fk.ReferencedTable.Name)} {#GetFkObjectName(fk)} { get; set; }
{/for} {/for}
internal static IFreeSql mysql => Const.mysql; internal static IFreeSql freesql => Const.mysql;
public static ISelect<{#UString(table.Name)}> Select => mysql.Select<{#UString(table.Name)}>(); public static ISelect<{#UString(table.Name)}> Select => freesql.Select<{#UString(table.Name)}>();
{if (table.Uniques.Count > 0)} {if (table.Uniques.Count > 0)}
public static int ItemCacheTimeout = 180;{for uk001 in table.Uniques}{% public static int ItemCacheTimeout = 180;{for uk001 in table.Uniques}{%
@ -79,7 +79,7 @@ namespace test.Model {
parmsNodeTypeUpdateCacheRemove = parmsNodeTypeUpdateCacheRemove.Substring(0, parmsNodeTypeUpdateCacheRemove.Length - 9); parmsNodeTypeUpdateCacheRemove = parmsNodeTypeUpdateCacheRemove.Substring(0, parmsNodeTypeUpdateCacheRemove.Length - 9);
%} %}
public static {#UString(table.Name)} GetItem{#uk001[0].IsPrimary ? string.Empty : parmsBy}({#parms}) => Select.Where(a => {#parmsByWhereLambda}).Caching(ItemCacheTimeout, string.Concat("test:{#table.Name}{#uk001[0].IsPrimary ? string.Empty : parmsBy}:", {#parmsNodeTypeUpdateCacheRemove.Replace("item.", "")})).ToOne();{/for} public static {#UString(table.Name)} GetItem{#uk001[0].IsPrimary ? string.Empty : parmsBy}({#parms}) => Select.Where(a => {#parmsByWhereLambda}).Caching(ItemCacheTimeout, string.Concat("test:{#table.Name}{#uk001[0].IsPrimary ? string.Empty : parmsBy}:", {#parmsNodeTypeUpdateCacheRemove.Replace("item.", "")})).ToOne();{/for}
{/if}{if (table.Uniques.Count > 0)}{for uk001 in table.Uniques}{% {for uk001 in table.Uniques}{%
string parms = string.Empty; string parms = string.Empty;
string parmsByWhereLambda = string.Empty; string parmsByWhereLambda = string.Empty;
@ -101,12 +101,12 @@ namespace test.Model {
parmsNoneType = parmsNoneType.Substring(0, parmsNoneType.Length - 2); parmsNoneType = parmsNoneType.Substring(0, parmsNoneType.Length - 2);
%} %}
public static long Delete{#uk001[0].IsPrimary ? string.Empty : parmsBy}({#parms}) { public static long Delete{#uk001[0].IsPrimary ? string.Empty : parmsBy}({#parms}) {
var affrows = mysql.Delete<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows();{if table.Uniques.Count > 1} var affrows = freesql.Delete<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows();{if table.Uniques.Count > 1}
if (ItemCacheTimeout > 0) RemoveCache(GetItem{#uk001[0].IsPrimary ? string.Empty : parmsBy}({#parmsNoneType}));{else} if (ItemCacheTimeout > 0) RemoveCache(GetItem{#uk001[0].IsPrimary ? string.Empty : parmsBy}({#parmsNoneType}));{else}
if (ItemCacheTimeout > 0) RemoveCache(new {#UString(table.Name)} { {#parmsNewItem} });{/if} if (ItemCacheTimeout > 0) RemoveCache(new {#UString(table.Name)} { {#parmsNewItem} });{/if}
return affrows; return affrows;
}{/for} }{/for}
{/if}{for fkcoldel in fks}{% {for fkcoldel in fks}{%
string parms = string.Empty; string parms = string.Empty;
string parmsBy = "By"; string parmsBy = "By";
string parmsByWhereLambda = string.Empty; string parmsByWhereLambda = string.Empty;
@ -121,9 +121,9 @@ namespace test.Model {
parmsByWhereLambda = parmsByWhereLambda.Substring(0, parmsByWhereLambda.Length - 4); parmsByWhereLambda = parmsByWhereLambda.Substring(0, parmsByWhereLambda.Length - 4);
%} %}
public static long DeleteBy{#parmsBy}({#parms}) { public static long DeleteBy{#parmsBy}({#parms}) {
return mysql.Delete<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows(); //删除缓存 return freesql.Delete<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows(); //删除缓存
} }
{/for}{if (table.Uniques.Count > 0)}{% string redisRemoveCode = string.Empty; %}{for uk001 in table.Uniques}{% {/for}{% string redisRemoveCode = string.Empty; %}{for uk001 in table.Uniques}{%
string parmsBy = "By"; string parmsBy = "By";
string parmsNodeTypeUpdateCacheRemove = string.Empty; string parmsNodeTypeUpdateCacheRemove = string.Empty;
@ -143,10 +143,10 @@ namespace test.Model {
var keysIdx = 0; var keysIdx = 0;
foreach (var item in items) {{#redisRemoveCode} foreach (var item in items) {{#redisRemoveCode}
} }
if (mysql.Ado.TransactionCurrentThread != null) mysql.Ado.TransactionPreRemoveCache(keys); if (freesql.Ado.TransactionCurrentThread != null) freesql.Ado.TransactionPreRemoveCache(keys);
else mysql.Cache.Remove(keys); else freesql.Cache.Remove(keys);
} }
{/if}{if (table.Columns.Count < 100)}{% {if (table.Columns.Count < 100)}{%
string CsParam3 = string.Empty; string CsParam3 = string.Empty;
string CsParamNoType3 = string.Empty; string CsParamNoType3 = string.Empty;
string parms = string.Empty; string parms = string.Empty;
@ -186,55 +186,55 @@ namespace test.Model {
if (CsParamNoType3.Length > 0) CsParamNoType3 = CsParamNoType3.Substring(0, CsParamNoType3.Length - 2); if (CsParamNoType3.Length > 0) CsParamNoType3 = CsParamNoType3.Substring(0, CsParamNoType3.Length - 2);
%}{if idens > 0} %}{if idens > 0}
public static {#GetCsType(idensCol)} Insert({#UString(table.Name)} item) { public static {#GetCsType(idensCol)} Insert({#UString(table.Name)} item) {
item.{#UString(idensCol.Name)} = ({#GetCsType(idensCol)})mysql.Insert<{#UString(table.Name)}>().AppendData(item).ExecuteIdentity(); item.{#UString(idensCol.Name)} = ({#GetCsType(idensCol)})freesql.Insert<{#UString(table.Name)}>().AppendData(item).ExecuteIdentity();
if (ItemCacheTimeout > 0) RemoveCache(item); if (ItemCacheTimeout > 0) RemoveCache(item);
return item.{#UString(idensCol.Name)}; return item.{#UString(idensCol.Name)};
}{else} }{else}
public static void Insert({#UString(table.Name)} item) { public static void Insert({#UString(table.Name)} item) {
if (ItemCacheTimeout > 0) RemoveCache(item); if (ItemCacheTimeout > 0) RemoveCache(item);
mysql.Insert<{#UString(table.Name)}>().AppendData(item).ExecuteAffrows(); freesql.Insert<{#UString(table.Name)}>().AppendData(item).ExecuteAffrows();
} }
public static long Insert(IEnumerable<{#UString(table.Name)}> items) { public static long Insert(IEnumerable<{#UString(table.Name)}> items) {
if (ItemCacheTimeout > 0) RemoveCache(items); if (ItemCacheTimeout > 0) RemoveCache(items);
return mysql.Insert<{#UString(table.Name)}>().AppendData(items).ExecuteAffrows(); return freesql.Insert<{#UString(table.Name)}>().AppendData(items).ExecuteAffrows();
}{/if} }{/if}
{if CsParamNoType3.Split('=').Length <= 5}{if idens > 0} {if CsParamNoType3.Split('=').Length <= 5}{if idens > 0}
public static {#GetCsType(idensCol)} Insert({#CsParam3}) { public static {#GetCsType(idensCol)} Insert({#CsParam3}) {
var item = new {#UString(table.Name)} {{#CsParamNoType3}}; var item = new {#UString(table.Name)} {{#CsParamNoType3}};
item.{#UString(idensCol.Name)} = ({#GetCsType(idensCol)})mysql.Insert<{#UString(table.Name)}>().AppendData(new {#UString(table.Name)} {{#CsParamNoType3}}).ExecuteIdentity(); item.{#UString(idensCol.Name)} = ({#GetCsType(idensCol)})freesql.Insert<{#UString(table.Name)}>().AppendData(new {#UString(table.Name)} {{#CsParamNoType3}}).ExecuteIdentity();
if (ItemCacheTimeout > 0) RemoveCache(item); if (ItemCacheTimeout > 0) RemoveCache(item);
return item.{#UString(idensCol.Name)}; return item.{#UString(idensCol.Name)};
}{else} }{else}
public static {#UString(table.Name)} Insert({#CsParam3}) { public static {#UString(table.Name)} Insert({#CsParam3}) {
var item = new {#UString(table.Name)} {{#CsParamNoType3}}; var item = new {#UString(table.Name)} {{#CsParamNoType3}};
mysql.Insert<{#UString(table.Name)}>().AppendData(item).ExecuteAffrows(); freesql.Insert<{#UString(table.Name)}>().AppendData(item).ExecuteAffrows();
if (ItemCacheTimeout > 0) RemoveCache(item); if (ItemCacheTimeout > 0) RemoveCache(item);
return item; return item;
}{/if}{/if} }{/if}{/if}
public static long Update({#UString(table.Name)} item) { public static long Update({#UString(table.Name)} item) {
if (ItemCacheTimeout > 0) RemoveCache(item); if (ItemCacheTimeout > 0) RemoveCache(item);
return mysql.Update<{#UString(table.Name)}>().SetSource(item).ExecuteAffrows(); return freesql.Update<{#UString(table.Name)}>().SetSource(item).ExecuteAffrows();
} }
public static long Update(IEnumerable<{#UString(table.Name)}> items) { public static long Update(IEnumerable<{#UString(table.Name)}> items) {
if (ItemCacheTimeout > 0) RemoveCache(items); if (ItemCacheTimeout > 0) RemoveCache(items);
return mysql.Update<{#UString(table.Name)}>().SetSource(items).ExecuteAffrows(); return freesql.Update<{#UString(table.Name)}>().SetSource(items).ExecuteAffrows();
} }
/// <summary> /// <summary>
/// 指定字段更新 /// 指定字段更新
/// </summary> /// </summary>
public IUpdate<{#UString(table.Name)}> UpdateDiy => mysql.Update<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}); public IUpdate<{#UString(table.Name)}> UpdateDiy => freesql.Update<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda});
/// <summary> /// <summary>
/// {if pks.Count > 0}保存或添加,如果主键有值则尝试 Update如果影响的行为 0 则尝试 Insert{else}添加{/if} /// {if pks.Count > 0}保存或添加,如果主键有值则尝试 Update如果影响的行为 0 则尝试 Insert{else}添加{/if}
/// </summary> /// </summary>
public void Save() {{if pks.Count > 0} public void Save() {{if pks.Count > 0}
if ({#string.Join(" && ", pks.Select(pkssa => "this." + UString(pkssa.Name) + " != default(" + GetCsType(pkssa) + ")"))}) { if ({#string.Join(" && ", pks.Select(pkssa => "this." + UString(pkssa.Name) + " != default(" + GetCsType(pkssa) + ")"))}) {
var affrows = mysql.Update<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows(); var affrows = freesql.Update<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows();
if (affrows > 0) return; if (affrows > 0) return;
}{/if} }{/if}
{if idens > 0}this.{#UString(idensCol.Name)} = {#GetCsType(idensCol).Replace("?", "") == "long" ? "" : ("(" + GetCsType(idensCol) + ")")}mysql.Insert<{#UString(table.Name)}>().AppendData(this).ExecuteIdentity();{else} {if idens > 0}this.{#UString(idensCol.Name)} = {#GetCsType(idensCol).Replace("?", "") == "long" ? "" : ("(" + GetCsType(idensCol) + ")")}freesql.Insert<{#UString(table.Name)}>().AppendData(this).ExecuteIdentity();{else}
mysql.Insert<{#UString(table.Name)}>().AppendData(this).ExecuteAffrows();{/if} freesql.Insert<{#UString(table.Name)}>().AppendData(this).ExecuteAffrows();{/if}
} }
{/if} {/if}{/if}
} }
{include ../../include/enumtype.tpl} {include ../../include/enumtype.tpl}
} }

View File

@ -0,0 +1,94 @@
# 生成器
生成器是基于 dbfirst 开发的辅助工具,适用老项目一键生成实体。生成器采用模板的方式,作者实现了三种生成模板:
| 模板名称 | 类型映射 | 外键导航属性 | 缓存管理 | 失血 | 贫血 | 充血 |
| ------------- | - | - |- | - |- | - |
| simple-entity | √ | X | X | √ | X | X |
| simple-entity-navigation-object | √ | √ | X | √ | X | X |
| rich-entity-navigation-object | √ | √ | √ | X | √ | X |
模板在项目目录:/Templates/MySql
> 更多模板逐步开发中。。。
```csharp
//定义 mysql FreeSql
var mysql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10")
.Build();
//创建模板生成类现实
var gen = new FreeSql.Generator.TemplateGenerator();
gen.Build(mysql.DbFirst,
@"C:\Users\28810\Desktop\github\FreeSql\Templates\MySql\simple-entity", //模板目录(事先下载)
@"C:\Users\28810\Desktop\新建文件夹 (9)", //生成后保存的目录
"cccddd" //数据库
);
```
## 模板语法
```html
<html>
<head>
<title>{#title}</title>
</head>
<body>
<!--绑定表达式-->
{#表达式}
{##表达式} 当表达式可能发生runtime错误时使用性能没有上面的高
<!--可嵌套使用同一标签最多支持3个指令-->
{include ../header.html}
<div @for="i 1, 101">
<p @if="i === 50" @for="item,index in data">aaa</p>
<p @else="i % 3 === 0">bbb {#i}</p>
<p @else="">ccc {#i}</p>
</div>
<!--定义模块,可以将公共模块定义到一个文件中-->
{module module_name1 parms1, 2, 3...}
{/module}
{module module_name2 parms1, 2, 3...}
{/module}
<!--使用模块-->
{import ../module.html as myname}
{#myname.module_name(parms1, 2, 3...)}
<!--继承-->
{extends ../inc/layout.html}
{block body}{/block}
<!--嵌入代码块-->
{%
for (var a = 0; a < 100; a++)
print(a);
%}
<!--条件分支-->
{if i === 50}
{elseif i > 60}
{else}
{/if}
<!--三种循环-->
{for i 1,101} 可自定义名 {for index2 表达式1 in 表达式2}
{for item,index in items} 可选参数称 index
可自定义名 {for item2, index99 in 数组表达式}
{for key,item,index on json} 可选参数 item, index
可自定义名 {for key2, item2, index99 in 对象表达式}
{/for}
<!--不被解析-->
{miss}
此块内容不被bmw.js解析
{/miss}
</body>
</html>
```

View File

@ -0,0 +1,94 @@
# 生成器
生成器是基于 dbfirst 开发的辅助工具,适用老项目一键生成实体。生成器采用模板的方式,作者实现了三种生成模板:
| 模板名称 | 类型映射 | 外键导航属性 | 缓存管理 | 失血 | 贫血 | 充血 |
| ------------- | - | - |- | - |- | - |
| simple-entity | √ | X | X | √ | X | X |
| simple-entity-navigation-object | √ | √ | X | √ | X | X |
| rich-entity-navigation-object | √ | √ | √ | X | √ | X |
模板在项目目录:/Templates/MySql
> 更多模板逐步开发中。。。
```csharp
//定义 mysql FreeSql
var mysql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10")
.Build();
//创建模板生成类现实
var gen = new FreeSql.Generator.TemplateGenerator();
gen.Build(mysql.DbFirst,
@"C:\Users\28810\Desktop\github\FreeSql\Templates\MySql\simple-entity", //模板目录(事先下载)
@"C:\Users\28810\Desktop\新建文件夹 (9)", //生成后保存的目录
"cccddd" //数据库
);
```
## 模板语法
```html
<html>
<head>
<title>{#title}</title>
</head>
<body>
<!--绑定表达式-->
{#表达式}
{##表达式} 当表达式可能发生runtime错误时使用性能没有上面的高
<!--可嵌套使用同一标签最多支持3个指令-->
{include ../header.html}
<div @for="i 1, 101">
<p @if="i === 50" @for="item,index in data">aaa</p>
<p @else="i % 3 === 0">bbb {#i}</p>
<p @else="">ccc {#i}</p>
</div>
<!--定义模块,可以将公共模块定义到一个文件中-->
{module module_name1 parms1, 2, 3...}
{/module}
{module module_name2 parms1, 2, 3...}
{/module}
<!--使用模块-->
{import ../module.html as myname}
{#myname.module_name(parms1, 2, 3...)}
<!--继承-->
{extends ../inc/layout.html}
{block body}{/block}
<!--嵌入代码块-->
{%
for (var a = 0; a < 100; a++)
print(a);
%}
<!--条件分支-->
{if i === 50}
{elseif i > 60}
{else}
{/if}
<!--三种循环-->
{for i 1,101} 可自定义名 {for index2 表达式1 in 表达式2}
{for item,index in items} 可选参数称 index
可自定义名 {for item2, index99 in 数组表达式}
{for key,item,index on json} 可选参数 item, index
可自定义名 {for key2, item2, index99 in 对象表达式}
{/for}
<!--不被解析-->
{miss}
此块内容不被bmw.js解析
{/miss}
</body>
</html>
```

View File

@ -0,0 +1,94 @@
# 生成器
生成器是基于 dbfirst 开发的辅助工具,适用老项目一键生成实体。生成器采用模板的方式,作者实现了三种生成模板:
| 模板名称 | 类型映射 | 外键导航属性 | 缓存管理 | 失血 | 贫血 | 充血 |
| ------------- | - | - |- | - |- | - |
| simple-entity | √ | X | X | √ | X | X |
| simple-entity-navigation-object | √ | √ | X | √ | X | X |
| rich-entity-navigation-object | √ | √ | √ | X | √ | X |
模板在项目目录:/Templates/MySql
> 更多模板逐步开发中。。。
```csharp
//定义 mysql FreeSql
var mysql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10")
.Build();
//创建模板生成类现实
var gen = new FreeSql.Generator.TemplateGenerator();
gen.Build(mysql.DbFirst,
@"C:\Users\28810\Desktop\github\FreeSql\Templates\MySql\simple-entity", //模板目录(事先下载)
@"C:\Users\28810\Desktop\新建文件夹 (9)", //生成后保存的目录
"cccddd" //数据库
);
```
## 模板语法
```html
<html>
<head>
<title>{#title}</title>
</head>
<body>
<!--绑定表达式-->
{#表达式}
{##表达式} 当表达式可能发生runtime错误时使用性能没有上面的高
<!--可嵌套使用同一标签最多支持3个指令-->
{include ../header.html}
<div @for="i 1, 101">
<p @if="i === 50" @for="item,index in data">aaa</p>
<p @else="i % 3 === 0">bbb {#i}</p>
<p @else="">ccc {#i}</p>
</div>
<!--定义模块,可以将公共模块定义到一个文件中-->
{module module_name1 parms1, 2, 3...}
{/module}
{module module_name2 parms1, 2, 3...}
{/module}
<!--使用模块-->
{import ../module.html as myname}
{#myname.module_name(parms1, 2, 3...)}
<!--继承-->
{extends ../inc/layout.html}
{block body}{/block}
<!--嵌入代码块-->
{%
for (var a = 0; a < 100; a++)
print(a);
%}
<!--条件分支-->
{if i === 50}
{elseif i > 60}
{else}
{/if}
<!--三种循环-->
{for i 1,101} 可自定义名 {for index2 表达式1 in 表达式2}
{for item,index in items} 可选参数称 index
可自定义名 {for item2, index99 in 数组表达式}
{for key,item,index on json} 可选参数 item, index
可自定义名 {for key2, item2, index99 in 对象表达式}
{/for}
<!--不被解析-->
{miss}
此块内容不被bmw.js解析
{/miss}
</body>
</html>
```

View File

@ -0,0 +1,5 @@
public static class Const {
public static IFreeSql sqlserver = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10")
.Build();
}

View File

@ -0,0 +1,240 @@
{%if (table.Type == DbTableType.StoreProcedure) {
print("return;");
return rTn;
}
%}using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Newtonsoft.Json;
using FreeSql;
using FreeSql.DataAnnotations;
{%
var dbf = dbfirst as FreeSql.IDbFirst;
var cols = (table.Columns as List<DbColumnInfo>);
var pks = (table.Primarys as List<DbColumnInfo>);
var fks = (table.Foreigns as List<DbForeignInfo>);
Func<string, string> UString = stra => stra.Substring(0, 1).ToUpper() + stra.Substring(1);
Func<DbColumnInfo, string> GetCsType = cola3 => {
return dbf.GetCsType(cola3);
};
Func<DbForeignInfo, string> GetFkObjectName = fkx => {
var eqfks = fks.Where(fk22a => fk22a.ReferencedTable.Name == fkx.ReferencedTable.Name);
if (eqfks.Count() == 1) return "Obj_" + fkx.ReferencedTable.Name;
var fkretname = fkx.Columns[0].Name;
if (fkretname.EndsWith(fkx.ReferencedColumns[0].Name, StringComparison.CurrentCultureIgnoreCase)) fkretname = fkretname.Substring(0, fkretname.Length - fkx.ReferencedColumns[0].Name.Length).TrimEnd('_');
if (fkretname.EndsWith(fkx.ReferencedTable.Name, StringComparison.CurrentCultureIgnoreCase)) fkretname = fkretname.Substring(0, fkretname.Length - fkx.ReferencedTable.Name.Length).TrimEnd('_');
if (fkretname.StartsWith(fkx.ReferencedTable.Name, StringComparison.CurrentCultureIgnoreCase)) fkretname = fkretname.Substring(fkx.ReferencedTable.Name.Length).TrimStart('_');
return "Obj_" + fkx.ReferencedTable.Name + (string.IsNullOrEmpty(fkretname) ? "" : ("_" + fkretname));
};
%}
namespace test.Model {
[JsonObject(MemberSerialization.OptIn), Table(Name = "{#!string.IsNullOrEmpty(table.Schema) ? table.Schema + "." : ""}{#table.Name}"{if cols.Where(cola003 => cola003.Name.ToLower() == "is_deleted" || cola003.Name.ToLower() == "isdeleted").Any()}, SelectFilter = "a.IsDeleted = 1"{/if})]
public partial class {#UString(table.Name)} {{for col,index in table.Columns}{%
var findfks = fks.Where(fkaa => fkaa.Columns.Where(fkaac1 => fkaac1.Name == col.Name).Any());
%}{if findfks.Any() == false}
{if string.IsNullOrEmpty(col.Coment) == false}/// <summary>
/// {#col.Coment.Replace("\r\n", "\n").Replace("\n", "\r\n /// ")}
/// </summary>{/if}
[JsonProperty, Column(Name = "{#col.Name}", DbType = "{#col.DbTypeTextFull}"{if col.IsPrimary == true}, IsPrimary = true{/if}{if col.IsIdentity == true}, IsIdentity = true{/if}{if col.IsNullable == true}, IsNullable = true{/if})]
public {#GetCsType(col)} {#UString(col.Name)} { get; set; }
{else}
private {#GetCsType(col)} _{#UString(col.Name)};
{if string.IsNullOrEmpty(col.Coment) == false}/// <summary>
/// {#col.Coment.Replace("\r\n", "\n").Replace("\n", "\r\n /// ")}
/// </summary>{/if}
[JsonProperty, Column(Name = "{#col.Name}", DbType = "{#col.DbTypeTextFull}"{if col.IsPrimary == true}, IsPrimary = true{/if}{if col.IsIdentity == true}, IsIdentity = true{/if}{if col.IsNullable == true}, IsNullable = true{/if})]
public {#GetCsType(col)} {#UString(col.Name)} { get => _{#UString(col.Name)}; set {
if (_{#UString(col.Name)} == value) return;
_{#UString(col.Name)} = value;{for fkcok2 in findfks}
{#GetFkObjectName(fkcok2)} = null;{/for}
} }
{/if}{/for}{for fk in fks}
public {#UString(fk.ReferencedTable.Name)} {#GetFkObjectName(fk)} { get; set; }
{/for}
internal static IFreeSql freesql => Const.sqlserver;
public static ISelect<{#UString(table.Name)}> Select => freesql.Select<{#UString(table.Name)}>();
{if (table.Uniques.Count > 0)}
public static int ItemCacheTimeout = 180;{for uk001 in table.Uniques}{%
string parms = string.Empty;
string parmsByWhereLambda = string.Empty;
string parmsBy = "By";
string parmsNodeTypeUpdateCacheRemove = string.Empty;
foreach (var uk001col in uk001) {
string getcstype = GetCsType(uk001col);
parms += getcstype.Replace("?", "") + " " + UString(uk001col.Name) + ", ";
parmsByWhereLambda += "a." + UString(uk001col.Name) + " == " + UString(uk001col.Name) + " && ";
parmsBy += UString(uk001col.Name) + "And";
parmsNodeTypeUpdateCacheRemove += "item." + UString(uk001col.Name) + ", \"_,_\", ";
}
parms = parms.Substring(0, parms.Length - 2);
parmsByWhereLambda = parmsByWhereLambda.Substring(0, parmsByWhereLambda.Length - 4);
parmsBy = parmsBy.Substring(0, parmsBy.Length - 3);
parmsNodeTypeUpdateCacheRemove = parmsNodeTypeUpdateCacheRemove.Substring(0, parmsNodeTypeUpdateCacheRemove.Length - 9);
%}
public static {#UString(table.Name)} GetItem{#uk001[0].IsPrimary ? string.Empty : parmsBy}({#parms}) => Select.Where(a => {#parmsByWhereLambda}).Caching(ItemCacheTimeout, string.Concat("test:{#table.Name}{#uk001[0].IsPrimary ? string.Empty : parmsBy}:", {#parmsNodeTypeUpdateCacheRemove.Replace("item.", "")})).ToOne();{/for}
{for uk001 in table.Uniques}{%
string parms = string.Empty;
string parmsByWhereLambda = string.Empty;
string parmsNewItem = string.Empty;
string parmsBy = "By";
string parmsNoneType = string.Empty;
foreach (var uk001col in uk001) {
string getcstype = GetCsType(uk001col);
parms += getcstype.Replace("?", "") + " " + UString(uk001col.Name) + ", ";
parmsByWhereLambda += "a." + UString(uk001col.Name) + " == " + UString(uk001col.Name) + " && ";
parmsNewItem += UString(uk001col.Name) + " = " + UString(uk001col.Name) + ", ";
parmsBy += UString(uk001col.Name) + "And";
parmsNoneType += UString(uk001col.Name) + ", ";
}
parms = parms.Substring(0, parms.Length - 2);
parmsByWhereLambda = parmsByWhereLambda.Substring(0, parmsByWhereLambda.Length - 4);
parmsNewItem = parmsNewItem.Substring(0, parmsNewItem.Length - 2);
parmsBy = parmsBy.Substring(0, parmsBy.Length - 3);
parmsNoneType = parmsNoneType.Substring(0, parmsNoneType.Length - 2);
%}
public static long Delete{#uk001[0].IsPrimary ? string.Empty : parmsBy}({#parms}) {
var affrows = freesql.Delete<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows();{if table.Uniques.Count > 1}
if (ItemCacheTimeout > 0) RemoveCache(GetItem{#uk001[0].IsPrimary ? string.Empty : parmsBy}({#parmsNoneType}));{else}
if (ItemCacheTimeout > 0) RemoveCache(new {#UString(table.Name)} { {#parmsNewItem} });{/if}
return affrows;
}{/for}
{for fkcoldel in fks}{%
string parms = string.Empty;
string parmsBy = "By";
string parmsByWhereLambda = string.Empty;
foreach( var fkcoldelcol in fkcoldel.Columns) {
string getcstype = GetCsType(fkcoldelcol);
parms += getcstype.Replace("?", "") + " " + UString(fkcoldelcol.Name) + ", ";
parmsBy += UString(fkcoldelcol.Name) + "And";
parmsByWhereLambda += "a." + UString(fkcoldelcol.Name) + " == " + UString(fkcoldelcol.Name) + " && ";
}
parms = parms.Substring(0, parms.Length - 2);
parmsBy = parmsBy.Substring(0, parmsBy.Length - 3);
parmsByWhereLambda = parmsByWhereLambda.Substring(0, parmsByWhereLambda.Length - 4);
%}
public static long DeleteBy{#parmsBy}({#parms}) {
return freesql.Delete<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows(); //删除缓存
}
{/for}{% string redisRemoveCode = string.Empty; %}{for uk001 in table.Uniques}{%
string parmsBy = "By";
string parmsNodeTypeUpdateCacheRemove = string.Empty;
foreach (var uk001col in uk001) {
parmsBy += UString(uk001col.Name) + "And";
parmsNodeTypeUpdateCacheRemove += "item." + UString(uk001col.Name) + ", \"_,_\", ";
}
parmsBy = parmsBy.Substring(0, parmsBy.Length - 3);
parmsNodeTypeUpdateCacheRemove = parmsNodeTypeUpdateCacheRemove.Substring(0, parmsNodeTypeUpdateCacheRemove.Length - 9);
redisRemoveCode += $@"
keys[keysIdx++] = string.Concat(""test:{table.Name}{(uk001[0].IsPrimary ? string.Empty : parmsBy)}:"", {parmsNodeTypeUpdateCacheRemove});";
%}{/for}
internal static void RemoveCache({#UString(table.Name)} item) => RemoveCache(item == null ? null : new [] { item });
internal static void RemoveCache(IEnumerable<{#UString(table.Name)}> items) {
if (ItemCacheTimeout <= 0 || items == null || items.Any() == false) return;
var keys = new string[items.Count() * {#table.Uniques.Count}];
var keysIdx = 0;
foreach (var item in items) {{#redisRemoveCode}
}
if (freesql.Ado.TransactionCurrentThread != null) freesql.Ado.TransactionPreRemoveCache(keys);
else freesql.Cache.Remove(keys);
}
{if (table.Columns.Count < 100)}{%
string CsParam3 = string.Empty;
string CsParamNoType3 = string.Empty;
string parms = string.Empty;
string parmsByWhereLambda = string.Empty;
string parmsNewItem = string.Empty;
string parmsBy = "By";
string parmsNoneType = string.Empty;
var idens = 0;
var idensCol = table.Columns[0];
foreach (var uk001col in table.Columns) {
string getcstype = GetCsType(uk001col);
parms += getcstype.Replace("?", "") + " " + UString(uk001col.Name) + ", ";
if (uk001col.IsPrimary)
parmsByWhereLambda += "a." + UString(uk001col.Name) + " == " + UString(uk001col.Name) + " && ";
parmsNewItem += UString(uk001col.Name) + " = " + UString(uk001col.Name) + ", ";
parmsBy += UString(uk001col.Name) + "And";
parmsNoneType += UString(uk001col.Name) + ", ";
if (uk001col.IsIdentity) {
idens++;
idensCol = uk001col;
} else {
if (getcstype.StartsWith("DateTime") && (uk001col.Name.ToLower() == "create_time" || uk001col.Name.ToLower() == "update_time" || uk001col.Name.ToLower() == "createtime" || uk001col.Name.ToLower() == "updatetime") ||
getcstype == "bool?" && (uk001col.Name.ToLower() == "is_deleted" || uk001col.Name.ToLower() == "isdeleted")) {
} else {
CsParam3 += getcstype + " " + UString(uk001col.Name) + ", ";
CsParamNoType3 += string.Format("\r\n {0} = {0}, ", UString(uk001col.Name));
}
}
}
parms = parms.Substring(0, parms.Length - 2);
if (parmsByWhereLambda.Length > 0) parmsByWhereLambda = parmsByWhereLambda.Substring(0, parmsByWhereLambda.Length - 4);
parmsNewItem = parmsNewItem.Substring(0, parmsNewItem.Length - 2);
parmsBy = parmsBy.Substring(0, parmsBy.Length - 3);
parmsNoneType = parmsNoneType.Substring(0, parmsNoneType.Length - 2);
if (CsParam3.Length > 0) CsParam3 = CsParam3.Substring(0, CsParam3.Length - 2);
if (CsParamNoType3.Length > 0) CsParamNoType3 = CsParamNoType3.Substring(0, CsParamNoType3.Length - 2);
%}{if idens > 0}
public static {#GetCsType(idensCol)} Insert({#UString(table.Name)} item) {
item.{#UString(idensCol.Name)} = ({#GetCsType(idensCol)})freesql.Insert<{#UString(table.Name)}>().AppendData(item).ExecuteIdentity();
if (ItemCacheTimeout > 0) RemoveCache(item);
return item.{#UString(idensCol.Name)};
}{else}
public static void Insert({#UString(table.Name)} item) {
if (ItemCacheTimeout > 0) RemoveCache(item);
freesql.Insert<{#UString(table.Name)}>().AppendData(item).ExecuteAffrows();
}
public static long Insert(IEnumerable<{#UString(table.Name)}> items) {
if (ItemCacheTimeout > 0) RemoveCache(items);
return freesql.Insert<{#UString(table.Name)}>().AppendData(items).ExecuteAffrows();
}{/if}
{if CsParamNoType3.Split('=').Length <= 5}{if idens > 0}
public static {#GetCsType(idensCol)} Insert({#CsParam3}) {
var item = new {#UString(table.Name)} {{#CsParamNoType3}};
item.{#UString(idensCol.Name)} = ({#GetCsType(idensCol)})freesql.Insert<{#UString(table.Name)}>().AppendData(new {#UString(table.Name)} {{#CsParamNoType3}}).ExecuteIdentity();
if (ItemCacheTimeout > 0) RemoveCache(item);
return item.{#UString(idensCol.Name)};
}{else}
public static {#UString(table.Name)} Insert({#CsParam3}) {
var item = new {#UString(table.Name)} {{#CsParamNoType3}};
freesql.Insert<{#UString(table.Name)}>().AppendData(item).ExecuteAffrows();
if (ItemCacheTimeout > 0) RemoveCache(item);
return item;
}{/if}{/if}
public static long Update({#UString(table.Name)} item) {
if (ItemCacheTimeout > 0) RemoveCache(item);
return freesql.Update<{#UString(table.Name)}>().SetSource(item).ExecuteAffrows();
}
public static long Update(IEnumerable<{#UString(table.Name)}> items) {
if (ItemCacheTimeout > 0) RemoveCache(items);
return freesql.Update<{#UString(table.Name)}>().SetSource(items).ExecuteAffrows();
}
/// <summary>
/// 指定字段更新
/// </summary>
public IUpdate<{#UString(table.Name)}> UpdateDiy => freesql.Update<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda});
/// <summary>
/// {if pks.Count > 0}保存或添加,如果主键有值则尝试 Update如果影响的行为 0 则尝试 Insert{else}添加{/if}
/// </summary>
public void Save() {{if pks.Count > 0}
if ({#string.Join(" && ", pks.Select(pkssa => "this." + UString(pkssa.Name) + " != default(" + GetCsType(pkssa) + ")"))}) {
var affrows = freesql.Update<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows();
if (affrows > 0) return;
}{/if}
{if idens > 0}this.{#UString(idensCol.Name)} = {#GetCsType(idensCol).Replace("?", "") == "long" ? "" : ("(" + GetCsType(idensCol) + ")")}freesql.Insert<{#UString(table.Name)}>().AppendData(this).ExecuteIdentity();{else}
freesql.Insert<{#UString(table.Name)}>().AppendData(this).ExecuteAffrows();{/if}
}
{/if}{/if}
}
}

View File

@ -0,0 +1,94 @@
# 生成器
生成器是基于 dbfirst 开发的辅助工具,适用老项目一键生成实体。生成器采用模板的方式,作者实现了三种生成模板:
| 模板名称 | 类型映射 | 外键导航属性 | 缓存管理 | 失血 | 贫血 | 充血 |
| ------------- | - | - |- | - |- | - |
| simple-entity | √ | X | X | √ | X | X |
| simple-entity-navigation-object | √ | √ | X | √ | X | X |
| rich-entity-navigation-object | √ | √ | √ | X | √ | X |
模板在项目目录:/Templates/MySql
> 更多模板逐步开发中。。。
```csharp
//定义 mysql FreeSql
var mysql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10")
.Build();
//创建模板生成类现实
var gen = new FreeSql.Generator.TemplateGenerator();
gen.Build(mysql.DbFirst,
@"C:\Users\28810\Desktop\github\FreeSql\Templates\MySql\simple-entity", //模板目录(事先下载)
@"C:\Users\28810\Desktop\新建文件夹 (9)", //生成后保存的目录
"cccddd" //数据库
);
```
## 模板语法
```html
<html>
<head>
<title>{#title}</title>
</head>
<body>
<!--绑定表达式-->
{#表达式}
{##表达式} 当表达式可能发生runtime错误时使用性能没有上面的高
<!--可嵌套使用同一标签最多支持3个指令-->
{include ../header.html}
<div @for="i 1, 101">
<p @if="i === 50" @for="item,index in data">aaa</p>
<p @else="i % 3 === 0">bbb {#i}</p>
<p @else="">ccc {#i}</p>
</div>
<!--定义模块,可以将公共模块定义到一个文件中-->
{module module_name1 parms1, 2, 3...}
{/module}
{module module_name2 parms1, 2, 3...}
{/module}
<!--使用模块-->
{import ../module.html as myname}
{#myname.module_name(parms1, 2, 3...)}
<!--继承-->
{extends ../inc/layout.html}
{block body}{/block}
<!--嵌入代码块-->
{%
for (var a = 0; a < 100; a++)
print(a);
%}
<!--条件分支-->
{if i === 50}
{elseif i > 60}
{else}
{/if}
<!--三种循环-->
{for i 1,101} 可自定义名 {for index2 表达式1 in 表达式2}
{for item,index in items} 可选参数称 index
可自定义名 {for item2, index99 in 数组表达式}
{for key,item,index on json} 可选参数 item, index
可自定义名 {for key2, item2, index99 in 对象表达式}
{/for}
<!--不被解析-->
{miss}
此块内容不被bmw.js解析
{/miss}
</body>
</html>
```

View File

@ -0,0 +1,59 @@
{%if (table.Type == DbTableType.StoreProcedure) {
print("return;");
return rTn;
}
%}using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Newtonsoft.Json;
using FreeSql.DataAnnotations;
{%
var dbf = dbfirst as FreeSql.IDbFirst;
var cols = (table.Columns as List<DbColumnInfo>);
var pks = (table.Primarys as List<DbColumnInfo>);
var fks = (table.Foreigns as List<DbForeignInfo>);
Func<string, string> UString = stra => stra.Substring(0, 1).ToUpper() + stra.Substring(1);
Func<DbColumnInfo, string> GetCsType = cola3 => {
return dbf.GetCsType(cola3);
};
Func<DbForeignInfo, string> GetFkObjectName = fkx => {
var eqfks = fks.Where(fk22a => fk22a.ReferencedTable.Name == fkx.ReferencedTable.Name);
if (eqfks.Count() == 1) return "Obj_" + fkx.ReferencedTable.Name;
var fkretname = fkx.Columns[0].Name;
if (fkretname.EndsWith(fkx.ReferencedColumns[0].Name, StringComparison.CurrentCultureIgnoreCase)) fkretname = fkretname.Substring(0, fkretname.Length - fkx.ReferencedColumns[0].Name.Length).TrimEnd('_');
if (fkretname.EndsWith(fkx.ReferencedTable.Name, StringComparison.CurrentCultureIgnoreCase)) fkretname = fkretname.Substring(0, fkretname.Length - fkx.ReferencedTable.Name.Length).TrimEnd('_');
if (fkretname.StartsWith(fkx.ReferencedTable.Name, StringComparison.CurrentCultureIgnoreCase)) fkretname = fkretname.Substring(fkx.ReferencedTable.Name.Length).TrimStart('_');
return "Obj_" + fkx.ReferencedTable.Name + (string.IsNullOrEmpty(fkretname) ? "" : ("_" + fkretname));
};
%}
namespace test.Model {
[JsonObject(MemberSerialization.OptIn), Table(Name = "{#!string.IsNullOrEmpty(table.Schema) ? table.Schema + "." : ""}{#table.Name}"{if cols.Where(cola003 => cola003.Name.ToLower() == "is_deleted" || cola003.Name.ToLower() == "isdeleted").Any()}, SelectFilter = "a.IsDeleted = 1"{/if})]
public partial class {#UString(table.Name)} {{for col,index in table.Columns}{%
var findfks = fks.Where(fkaa => fkaa.Columns.Where(fkaac1 => fkaac1.Name == col.Name).Any());
%}{if findfks.Any() == false}
{if string.IsNullOrEmpty(col.Coment) == false}/// <summary>
/// {#col.Coment.Replace("\r\n", "\n").Replace("\n", "\r\n /// ")}
/// </summary>{/if}
[JsonProperty, Column(Name = "{#col.Name}", DbType = "{#col.DbTypeTextFull}"{if col.IsPrimary == true}, IsPrimary = true{/if}{if col.IsIdentity == true}, IsIdentity = true{/if}{if col.IsNullable == true}, IsNullable = true{/if})]
public {#GetCsType(col)} {#UString(col.Name)} { get; set; }
{else}
private {#GetCsType(col)} _{#UString(col.Name)};
{if string.IsNullOrEmpty(col.Coment) == false}/// <summary>
/// {#col.Coment.Replace("\r\n", "\n").Replace("\n", "\r\n /// ")}
/// </summary>{/if}
[JsonProperty, Column(Name = "{#col.Name}", DbType = "{#col.DbTypeTextFull}"{if col.IsPrimary == true}, IsPrimary = true{/if}{if col.IsIdentity == true}, IsIdentity = true{/if}{if col.IsNullable == true}, IsNullable = true{/if})]
public {#GetCsType(col)} {#UString(col.Name)} { get => _{#UString(col.Name)}; set {
if (_{#UString(col.Name)} == value) return;
_{#UString(col.Name)} = value;{for fkcok2 in findfks}
{#GetFkObjectName(fkcok2)} = null;{/for}
} }
{/if}{/for}{for fk in fks}
public {#UString(fk.ReferencedTable.Name)} {#GetFkObjectName(fk)} { get; set; }
{/for}
}
}

View File

@ -0,0 +1,94 @@
# 生成器
生成器是基于 dbfirst 开发的辅助工具,适用老项目一键生成实体。生成器采用模板的方式,作者实现了三种生成模板:
| 模板名称 | 类型映射 | 外键导航属性 | 缓存管理 | 失血 | 贫血 | 充血 |
| ------------- | - | - |- | - |- | - |
| simple-entity | √ | X | X | √ | X | X |
| simple-entity-navigation-object | √ | √ | X | √ | X | X |
| rich-entity-navigation-object | √ | √ | √ | X | √ | X |
模板在项目目录:/Templates/MySql
> 更多模板逐步开发中。。。
```csharp
//定义 mysql FreeSql
var mysql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10")
.Build();
//创建模板生成类现实
var gen = new FreeSql.Generator.TemplateGenerator();
gen.Build(mysql.DbFirst,
@"C:\Users\28810\Desktop\github\FreeSql\Templates\MySql\simple-entity", //模板目录(事先下载)
@"C:\Users\28810\Desktop\新建文件夹 (9)", //生成后保存的目录
"cccddd" //数据库
);
```
## 模板语法
```html
<html>
<head>
<title>{#title}</title>
</head>
<body>
<!--绑定表达式-->
{#表达式}
{##表达式} 当表达式可能发生runtime错误时使用性能没有上面的高
<!--可嵌套使用同一标签最多支持3个指令-->
{include ../header.html}
<div @for="i 1, 101">
<p @if="i === 50" @for="item,index in data">aaa</p>
<p @else="i % 3 === 0">bbb {#i}</p>
<p @else="">ccc {#i}</p>
</div>
<!--定义模块,可以将公共模块定义到一个文件中-->
{module module_name1 parms1, 2, 3...}
{/module}
{module module_name2 parms1, 2, 3...}
{/module}
<!--使用模块-->
{import ../module.html as myname}
{#myname.module_name(parms1, 2, 3...)}
<!--继承-->
{extends ../inc/layout.html}
{block body}{/block}
<!--嵌入代码块-->
{%
for (var a = 0; a < 100; a++)
print(a);
%}
<!--条件分支-->
{if i === 50}
{elseif i > 60}
{else}
{/if}
<!--三种循环-->
{for i 1,101} 可自定义名 {for index2 表达式1 in 表达式2}
{for item,index in items} 可选参数称 index
可自定义名 {for item2, index99 in 数组表达式}
{for key,item,index on json} 可选参数 item, index
可自定义名 {for key2, item2, index99 in 对象表达式}
{/for}
<!--不被解析-->
{miss}
此块内容不被bmw.js解析
{/miss}
</body>
</html>
```

View File

@ -0,0 +1,33 @@
{%if (table.Type == DbTableType.StoreProcedure) {
print("return;");
return rTn;
}
%}using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Newtonsoft.Json;
using FreeSql.DataAnnotations;
{%
var dbf = dbfirst as FreeSql.IDbFirst;
var cols = (table.Columns as List<DbColumnInfo>);
Func<string, string> UString = stra => stra.Substring(0, 1).ToUpper() + stra.Substring(1);
Func<DbColumnInfo, string> GetCsType = cola3 => {
return dbf.GetCsType(cola3);
};
%}
namespace test.Model {
[JsonObject(MemberSerialization.OptIn), Table(Name = "{#!string.IsNullOrEmpty(table.Schema) ? table.Schema + "." : ""}{#table.Name}"{if cols.Where(cola003 => cola003.Name.ToLower() == "is_deleted" || cola003.Name.ToLower() == "isdeleted").Any()}, SelectFilter = "a.IsDeleted = 1"{/if})]
public partial class {#UString(table.Name)} {{for col,index in table.Columns}
{if string.IsNullOrEmpty(col.Coment) == false}/// <summary>
/// {#col.Coment.Replace("\r\n", "\n").Replace("\n", "\r\n /// ")}
/// </summary>{/if}
[JsonProperty, Column(Name = "{#col.Name}", DbType = "{#col.DbTypeTextFull}"{if col.IsPrimary == true}, IsPrimary = true{/if}{if col.IsIdentity == true}, IsIdentity = true{/if}{if col.IsNullable == true}, IsNullable = true{/if})]
public {#GetCsType(col)} {#UString(col.Name)} { get; set; }
{/for}
}
}

View File

@ -0,0 +1,94 @@
# 生成器
生成器是基于 dbfirst 开发的辅助工具,适用老项目一键生成实体。生成器采用模板的方式,作者实现了三种生成模板:
| 模板名称 | 类型映射 | 外键导航属性 | 缓存管理 | 失血 | 贫血 | 充血 |
| ------------- | - | - |- | - |- | - |
| simple-entity | √ | X | X | √ | X | X |
| simple-entity-navigation-object | √ | √ | X | √ | X | X |
| rich-entity-navigation-object | √ | √ | √ | X | √ | X |
模板在项目目录:/Templates/MySql
> 更多模板逐步开发中。。。
```csharp
//定义 mysql FreeSql
var mysql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10")
.Build();
//创建模板生成类现实
var gen = new FreeSql.Generator.TemplateGenerator();
gen.Build(mysql.DbFirst,
@"C:\Users\28810\Desktop\github\FreeSql\Templates\MySql\simple-entity", //模板目录(事先下载)
@"C:\Users\28810\Desktop\新建文件夹 (9)", //生成后保存的目录
"cccddd" //数据库
);
```
## 模板语法
```html
<html>
<head>
<title>{#title}</title>
</head>
<body>
<!--绑定表达式-->
{#表达式}
{##表达式} 当表达式可能发生runtime错误时使用性能没有上面的高
<!--可嵌套使用同一标签最多支持3个指令-->
{include ../header.html}
<div @for="i 1, 101">
<p @if="i === 50" @for="item,index in data">aaa</p>
<p @else="i % 3 === 0">bbb {#i}</p>
<p @else="">ccc {#i}</p>
</div>
<!--定义模块,可以将公共模块定义到一个文件中-->
{module module_name1 parms1, 2, 3...}
{/module}
{module module_name2 parms1, 2, 3...}
{/module}
<!--使用模块-->
{import ../module.html as myname}
{#myname.module_name(parms1, 2, 3...)}
<!--继承-->
{extends ../inc/layout.html}
{block body}{/block}
<!--嵌入代码块-->
{%
for (var a = 0; a < 100; a++)
print(a);
%}
<!--条件分支-->
{if i === 50}
{elseif i > 60}
{else}
{/if}
<!--三种循环-->
{for i 1,101} 可自定义名 {for index2 表达式1 in 表达式2}
{for item,index in items} 可选参数称 index
可自定义名 {for item2, index99 in 数组表达式}
{for key,item,index on json} 可选参数 item, index
可自定义名 {for key2, item2, index99 in 对象表达式}
{/for}
<!--不被解析-->
{miss}
此块内容不被bmw.js解析
{/miss}
</body>
</html>
```