From 9e0ae87ded431ea598bff03529845c9497ef07ea Mon Sep 17 00:00:00 2001 From: ct-9904 Date: Mon, 20 May 2024 22:48:08 +0900 Subject: [PATCH] add GenInsert() --- dn/SQLite_demo/Program.cs | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/dn/SQLite_demo/Program.cs b/dn/SQLite_demo/Program.cs index d183dac..3d064b7 100644 --- a/dn/SQLite_demo/Program.cs +++ b/dn/SQLite_demo/Program.cs @@ -44,7 +44,7 @@ class Program { Action Insert = x => { using (var cmd = new SQLiteCommand(cn)) { var param = (object? it) => new SQLiteParameter(null, it); - cmd.CommandText = $"INSERT INTO {SQLGen.GetTableName(typeof(Record))} VALUES(null, ?, ?, ?, ?)"; + cmd.CommandText = typeof(Record).GenInsert(); cmd.Parameters.AddRange(new[] { param(x.Name), param(x.Date), param(x.IsDone), param(x.Number) }); @@ -62,6 +62,8 @@ class Program { }; Array.ForEach(records, x => Insert(x)); + + // SELECT using (var ctx = new DataContext(cn)) { Action> Show = q => { @@ -145,14 +147,14 @@ static class SQLGen { var tabName = GetTableName(type); var res = new List(); - foreach (var field in typeInfo.DeclaredProperties) { + foreach (var property in typeInfo.DeclaredProperties) { - foreach (Attribute attr in field.GetCustomAttributes()) { + foreach (Attribute attr in property.GetCustomAttributes()) { if (attr.GetType() != typeof(ColumnAttribute)) continue; ColumnAttribute cAttr = (ColumnAttribute)attr; - var name = cAttr.Name != null ? cAttr.Name : field.Name; - var tyName = cAttr.DbType != null ? cAttr.DbType : MapTyName(field.PropertyType); + var name = cAttr.Name != null ? cAttr.Name : property.Name; + var tyName = cAttr.DbType != null ? cAttr.DbType : MapTyName(property.PropertyType); var primary = cAttr.IsPrimaryKey ? "PRIMARY KEY" : ""; res.Add($"{name} {tyName} {primary}"); } @@ -163,4 +165,23 @@ static class SQLGen { Console.WriteLine(result); return result; } + + static private Dictionary _insertStatementCache = new Dictionary(); + public static string GenInsert(this Type type) { + if (_insertStatementCache.ContainsKey(type)) { + return _insertStatementCache[type]; + } + + TypeInfo typeInfo = type.GetTypeInfo(); + var n = typeInfo.DeclaredProperties + .Where(p => { + var attr = p.GetCustomAttribute(typeof(ColumnAttribute)); + return attr != null && !((ColumnAttribute)attr).IsPrimaryKey; }) + .Count(); + var sub = string.Concat(Enumerable.Repeat(", ?", n)); + var result = $"INSERT INTO {type.GetTableName()} VALUES(null{sub})"; + Console.WriteLine("GenInsert: {0}", result); + _insertStatementCache[type] = result; + return result; + } } \ No newline at end of file -- 2.11.4.GIT