Skip to content

Commit a75ab2d

Browse files
committed
Mysql增加对元组的支持
1 parent 33cd58a commit a75ab2d

File tree

13 files changed

+275
-89
lines changed

13 files changed

+275
-89
lines changed

examples/Mysql/Models.cs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace Mysql
6+
{
7+
public class PageModel
8+
{
9+
public int UserId { get; set; }
10+
public string Keyword { get; set; }
11+
public int PageIndex { get; set; } = 1;
12+
public int PageSize { get; set; } = 10;
13+
}
14+
15+
public struct IdModel
16+
{
17+
public int Id { get; set; }
18+
}
19+
}

examples/Mysql/Program.cs

Lines changed: 49 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,91 @@
11
using Mysql.Model;
2+
using Mysql.Services;
23
using MyStaging.Common;
34
using MyStaging.Interface;
45
using MyStaging.Metadata;
56
using MyStaging.MySql.Generals;
67
using Newtonsoft.Json.Linq;
78
using System;
9+
using System.Collections.Generic;
810

911
namespace Mysql
1012
{
1113
public class Program
1214
{
15+
private static MysqlDbContext dbContext;
1316
static void Main(string[] args)
1417
{
15-
//IGeneralFactory factory = new GeneralFactory();
16-
//factory.CodeFirst(new MyStaging.Metadata.ProjectConfig()
17-
//{
18-
// ConnectionString = "server=127.0.0.1;user id=root;password=root;database=mystaging",
19-
// Mode = MyStaging.Metadata.GeneralMode.Db,
20-
// OutputDir = @"D:\MyGitHub\mystaging\examples\Mysql\Models",
21-
// ProjectName = "Mysql",
22-
// Provider = "MySql"
23-
//});
18+
var options = new StagingOptions("MySql", "server=127.0.0.1;user id=root;password=root;");
19+
dbContext = new MysqlDbContext(options);
2420

25-
var options = new MyStaging.Metadata.StagingOptions("MySql", "server=127.0.0.1;user id=root;password=root;");
26-
var context = new MysqlDbContext(options);
21+
AddUpdateDelete();
22+
Query();
23+
Transaction();
24+
Console.WriteLine("success.....");
25+
Console.ReadKey();
26+
}
2727

28+
static void Transaction()
29+
{
2830
var customer = new Customer { Name = "好久不见" };
2931

3032
try
3133
{
3234
// 测试事务
33-
context.BeginTransaction();
34-
context.Customer.Insert.Add(customer);
35-
context.CommitTransaction();
35+
dbContext.BeginTransaction();
36+
dbContext.Customer.Insert.Add(customer);
37+
List<Customer> li = new List<Customer>();
38+
li.Add(new Customer { Name = "test" });
39+
dbContext.Customer.Insert.AddRange(li).SaveChange();
40+
dbContext.Customer.Update.SetValue(a => a.Name, "12345").Where(f => f.Id == customer.Id).SaveChange();
41+
dbContext.CommitTransaction();
3642

37-
var nc = context.Customer.Select.Where(f => f.Id == customer.Id).ToOne();
43+
ArticleService articleService = new ArticleService(dbContext);
44+
var art = articleService.Detail(29);
45+
art = articleService.Update(art.id, "修改了标题", art.content);
46+
bool success = articleService.Delete(art.id);
3847
}
3948
catch (Exception e)
4049
{
4150
Console.WriteLine(e.Message);
4251
}
43-
//// 单个查询
44-
//var article = context.Customer.Select.Where(f => f.Id == 2 && f.Name == "Ron").ToOne();
45-
//// 列表查询,排序、分页、分组
46-
//var articles = context.Customer.Select.OrderBy(f => f.Id).Page(1, 10).GroupBy("Name").ToList();
47-
//// 表连接查询
48-
//var article = context.Article.Select.InnerJoin<Customer>("b", (a, b) => a.userid == b.Id).Where<Customer>(f => f.Id == 2).ToOne();
49-
//// 首字段查询,ToScalar 参数可以传递 Sql 参数,比如 SUM(x)
50-
//var id = context.Customer.Select.Where(f => f.Id == 2 && f.Name == "Ron").ToScalar<int>("Id");
51-
var a3 = context.Article.Update.SetValue(f => f.content, "未来已来,从这里开始").Where(f => f.id == 1).SaveChange();
52-
var article = new Article()
52+
}
53+
54+
static void Query()
55+
{
56+
// 单个查询
57+
var article = dbContext.Customer.Select.Where(f => f.Id == 2 && f.Name == "Ron").ToOne();
58+
// 列表查询,排序、分页、分组
59+
var articles = dbContext.Customer.Select.OrderBy(f => f.Name).Page(1, 10).GroupBy("Id,Name").ToList<(int id, string name)>("Id,Name");
60+
// 表连接查询
61+
var ac = dbContext.Article.Select.InnerJoin<Customer>("b", (a, b) => a.userid == b.Id).Where<Customer>(f => f.Id == 2).ToOne();
62+
// 首字段查询,ToScalar 参数可以传递 Sql 参数,比如 SUM(x)
63+
var id = dbContext.Customer.Select.Where(f => f.Id == 2 && f.Name == "Ron").ToScalar<int>("Id");
64+
}
65+
66+
static void AddUpdateDelete()
67+
{
68+
var art = new Article()
5369
{
5470
content = "你是谁?你从哪里来?要到哪里去?",
5571
createtime = DateTime.Now,
56-
userid = customer.Id,
72+
userid = 43,
5773
IP = "127.0.0.1",
5874
State = true,
5975
title = "振聋发聩的人生三问"
6076
};
6177

62-
var list = new System.Collections.Generic.List<Article>();
78+
var articles = new List<Article>();
6379
for (int i = 0; i < 10; i++)
6480
{
65-
list.Add(article);
81+
articles.Add(art);
6682
}
67-
var a2 = context.Article.Insert.Add(article);
68-
var affrows = context.Article.Insert.AddRange(list).SaveChange();
69-
Console.WriteLine(affrows);
70-
// context.Article.Delete.Where(f => f.id == a2.id).SaveChange();
83+
var a2 = dbContext.Article.Insert.Add(art);
84+
var affrows = dbContext.Article.Insert.AddRange(articles).SaveChange();
7185

72-
// Console.WriteLine(a2.id);
73-
74-
Console.WriteLine("success.....");
75-
Console.ReadKey();
86+
var a3 = dbContext.Article.Update.SetValue(f => f.content, "未来已来,从这里开始").Where(f => f.id == 1).SaveChange();
87+
var a4 = dbContext.Article.Select.OrderByDescing(f => f.createtime).ToOne();
88+
dbContext.Article.Delete.Where(f => f.id == a4.id).SaveChange();
7689
}
7790
}
7891
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
using Mysql.Model;
2+
using MyStaging.Function;
3+
using System;
4+
using System.Collections.Generic;
5+
using System.Diagnostics;
6+
using System.Text;
7+
using System.Threading.Tasks;
8+
9+
namespace Mysql.Services
10+
{
11+
public class ArticleService
12+
{
13+
private readonly MysqlDbContext dbContext;
14+
public ArticleService(MysqlDbContext dbContext)
15+
{
16+
this.dbContext = dbContext;
17+
}
18+
19+
public List<Article> List(PageModel model)
20+
{
21+
var build = dbContext.Article.Select.Page(model.PageIndex, model.PageSize).OrderByDescing(f => f.createtime);
22+
if (model.UserId > 0)
23+
{
24+
build.Where(f => f.userid == model.UserId);
25+
}
26+
27+
if (!string.IsNullOrEmpty(model.Keyword))
28+
{
29+
build.Where(f => f.title.Like(model.Keyword));
30+
}
31+
32+
return build.ToList();
33+
}
34+
35+
public Article Detail(int id)
36+
{
37+
if (id <= 0)
38+
{
39+
return null;
40+
}
41+
var detail = dbContext.Article.Select.Where(f => f.id == id).ToOne();
42+
43+
return detail;
44+
}
45+
46+
public Article Add(Article model)
47+
{
48+
49+
var detail = dbContext.Article.Select.Where(f => f.id == model.id).ToOne();
50+
51+
return detail;
52+
}
53+
54+
public Article Update(int id, string title, string content)
55+
{
56+
var article = dbContext.Article.Select.Where(f => f.id == id).ToOne();
57+
if (article == null)
58+
throw new KeyNotFoundException($"找不到Id={id} 的记录");
59+
60+
article = dbContext.Article.Update.SetValue(f => f.content, content)
61+
.SetValue(f => f.title, title)
62+
.Where(f => f.id == article.id)
63+
.SaveChange();
64+
65+
return article;
66+
}
67+
68+
public bool Delete(int id)
69+
{
70+
var article = dbContext.Article.Select.Where(f => f.id == id).ToOne();
71+
if (article == null)
72+
throw new KeyNotFoundException($"找不到Id={id} 的记录");
73+
74+
var affrows = dbContext.Article.Delete.Where(f => f.id == id).SaveChange();
75+
76+
return affrows > 0;
77+
}
78+
}
79+
}

src/MyStaging.MySql/Core/SelectBuilder`.cs

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -368,27 +368,12 @@ private void ResetFields(params string[] fields)
368368
/// <returns></returns>
369369
public List<TResult> ExecuteReader<TResult>(string cmdText)
370370
{
371-
var objType = typeof(TResult);
372-
var properties = MyStagingUtils.GetDbFields(typeof(TResult));
373371
List<TResult> list = new List<TResult>();
374372
SQLExecute execute = byMaster ? dbContext.ByMaster().Execute : dbContext.Execute;
375373
using var reader = execute.ExecuteDataReader(CommandType.Text, cmdText, Parameters.ToArray());
376374
while (reader.Read())
377375
{
378-
TResult obj = (TResult)Activator.CreateInstance(objType);
379-
foreach (var pi in properties)
380-
{
381-
var value = reader[pi.Name];
382-
if (value == DBNull.Value)
383-
continue;
384-
else if (pi.PropertyType.Name == "JToken")
385-
{
386-
pi.SetValue(obj, JToken.Parse(value.ToString()));
387-
}
388-
else
389-
pi.SetValue(obj, value);
390-
}
391-
376+
var obj = GetResult<TResult>(reader);
392377
list.Add(obj);
393378
};
394379

@@ -718,6 +703,7 @@ public ISelectBuilder<T> ByMaster()
718703

719704
public new void Clear()
720705
{
706+
this.UnionList.Clear();
721707
this.Parameters.Clear();
722708
this.WhereConditions.Clear();
723709
this.WhereExpressions.Clear();

src/MyStaging.MySql/Generals/GeneralFactory.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -447,7 +447,7 @@ private void GetPrimarykey(TableInfo table)
447447
#region Properties
448448
public GeneralConfig Config { get; set; }
449449
public List<TableInfo> Tables { get; set; }
450-
private SQLExecute SQLContext => new SQLExecute(new MySqlConnection(config.ConnectionString));
450+
private SQLExecute SQLContext => new SQLExecute(new MySqlConnection(config.ConnectionString), null);
451451

452452
#endregion
453453
}

src/MyStaging.MySql/MyStaging.MySql.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<PropertyGroup>
44
<TargetFramework>netstandard2.1</TargetFramework>
5-
<Version>3.0.5</Version>
5+
<Version>3.0.6</Version>
66
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
77
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
88
</PropertyGroup>

src/MyStaging.PostgreSQL/Core/SelectBuilder`.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,8 @@ public List<TResult> ExecuteReader<TResult>(string cmdText)
391391
return list;
392392
}
393393

394+
395+
394396
/// <summary>
395397
/// 该方法没有对sql注入进行参数化过滤
396398
/// </summary>
@@ -711,6 +713,7 @@ public ISelectBuilder<T> ByMaster()
711713

712714
public new void Clear()
713715
{
716+
this.UnionList.Clear();
714717
this.Parameters.Clear();
715718
this.WhereConditions.Clear();
716719
this.WhereExpressions.Clear();

src/MyStaging.PostgreSQL/Generals/GeneralFactory.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -594,7 +594,7 @@ from information_schema.table_constraints a
594594
};
595595
public GeneralConfig Config { get; set; }
596596
public List<TableInfo> Tables { get; set; }
597-
private SQLExecute SQLContext => new SQLExecute(new NpgsqlConnection(config.ConnectionString));
597+
private SQLExecute SQLContext => new SQLExecute(new NpgsqlConnection(config.ConnectionString), null);
598598
#endregion
599599
}
600600
}

src/MyStaging/Common/MyStagingUtils.cs

Lines changed: 1 addition & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Data;
66
using System.Linq.Expressions;
77
using System.Reflection;
8+
using System.Text.Json;
89

910
namespace MyStaging.Common
1011
{
@@ -78,36 +79,6 @@ public static void CopyProperty<T>(T targetObj, T sourceObj, BindingFlags flags
7879
}
7980
}
8081

81-
/// <summary>
82-
/// 将查询结果转换为元组对象
83-
/// </summary>
84-
/// <param name="objType">元组类型</param>
85-
/// <param name="dr">查询流</param>
86-
/// <param name="columnIndex">dr index</param>
87-
/// <returns></returns>
88-
protected static object GetValueTuple(Type objType, IDataReader dr, ref int columnIndex)
89-
{
90-
bool isTuple = objType.Namespace == "System" && objType.Name.StartsWith("ValueTuple`");
91-
if (isTuple)
92-
{
93-
FieldInfo[] fs = objType.GetFields();
94-
Type[] types = new Type[fs.Length];
95-
object[] parameters = new object[fs.Length];
96-
for (int i = 0; i < fs.Length; i++)
97-
{
98-
types[i] = fs[i].FieldType;
99-
parameters[i] = GetValueTuple(types[i], dr, ref columnIndex);
100-
}
101-
ConstructorInfo info = objType.GetConstructor(types);
102-
return info.Invoke(parameters);
103-
}
104-
++columnIndex;
105-
object dbValue = dr[columnIndex];
106-
dbValue = dbValue is DBNull ? null : dbValue;
107-
108-
return dbValue;
109-
}
110-
11182
/// <summary>
11283
/// 获取表达式成员名称
11384
/// </summary>

src/MyStaging/Core/DbContext.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ private SQLExecute CreateExecute()
219219
Connection = Options.Connection.GetConnection(Options.Name, byMaster);
220220
}
221221

222-
return new SQLExecute(Connection);
222+
return new SQLExecute(Connection, CurrentThreadTransaction);
223223
}
224224

225225
/// <summary>

0 commit comments

Comments
 (0)