Commit 406aa0b8 authored by 潘栩锋's avatar 潘栩锋 🚴

1.添加 SQLiteHelper 的测试项目

2.添加 SQLiteDbContext
parent 7859a866

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.572
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SQLiteHelper", "SQLiteHelper\SQLiteHelper.csproj", "{4CBABFAA-1C62-4510-AC63-A51EE5FD50FF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitTestProject1", "UnitTestProject1\UnitTestProject1.csproj", "{6F59F24F-4CBE-426B-AFD7-3174DE4CA263}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4CBABFAA-1C62-4510-AC63-A51EE5FD50FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4CBABFAA-1C62-4510-AC63-A51EE5FD50FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4CBABFAA-1C62-4510-AC63-A51EE5FD50FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4CBABFAA-1C62-4510-AC63-A51EE5FD50FF}.Release|Any CPU.Build.0 = Release|Any CPU
{6F59F24F-4CBE-426B-AFD7-3174DE4CA263}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6F59F24F-4CBE-426B-AFD7-3174DE4CA263}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6F59F24F-4CBE-426B-AFD7-3174DE4CA263}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6F59F24F-4CBE-426B-AFD7-3174DE4CA263}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8BF603AD-A07A-4676-B1AA-85E0490B9126}
EndGlobalSection
EndGlobal
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SQLite
{
public abstract class SQLiteDbContext
{
public List<IDBTable> DbSet = new List<IDBTable>();
public SQLiteHelper sqliteHelper;
string ConnectionString
{
get
{
return string.Format("Data Source={0};Version=3;", DBPath);
}
}
public string DBPath { get; set; } = @"test.sqlite3";
/// <summary>
/// 当前全部表的ID, 与 TbTableID 同步
/// </summary>
public Dictionary<IDBTable, Int64> IDs = new Dictionary<IDBTable, Int64>();
public SQLiteDbContext()
{
Constructor();
}
void Constructor()
{
sqliteHelper = new SQLiteHelper();
sqliteHelper.ConnectionString = ConnectionString;
var type = GetType();
foreach (var p in type.GetProperties())
{
if (typeof(IDBTable).IsAssignableFrom(p.PropertyType))
{
DbSet.Add(p.GetValue(this) as IDBTable);
}
}
foreach (IDBTable dBTable in DbSet)
{
dBTable.Init(ConnectionString);
IDs.Add(dBTable, 0);
}
}
void Build()
{
string directoryname = System.IO.Path.GetDirectoryName(DBPath);
if (!string.IsNullOrEmpty(directoryname) && !System.IO.Directory.Exists(directoryname))
System.IO.Directory.CreateDirectory(directoryname);
SQLiteConnection.CreateFile(DBPath);
foreach (IDBTable dBTable in DbSet)
dBTable.Create();
}
void Rebuild()
{
if (!System.IO.File.Exists(DBPath))
{
Build();
}
else
{
//把文件删除,重建
System.IO.File.Delete(DBPath);
Build();
}
}
void Load()
{
for (int i = 0; i < IDs.Count(); i++)
{
var table = IDs.Keys.ElementAt(i);
IDs[table] = LoadID(table.TableName);
}
}
long LoadID(string tablename)
{
string cmd = $"SELECT MAX(ID) FROM {tablename}";
var reponse = sqliteHelper.ExecuteScalar(cmd);
return System.Convert.ToInt64(reponse) + 1;
}
/// <summary>
/// 给定分区数 检测表是否存在,合法
/// </summary>
/// <param name="nbolts"></param>
/// <returns>false 表不合法,重建; true 正常!</returns>
public bool Init()
{
if (!System.IO.File.Exists(DBPath))
{
Build();
return false;
}
//TODO, 表不对删除就好。。。没必要重新创建数据库
//任意一个表不对,或者不存在,都必须重建
Dictionary<string, string> ddls = new Dictionary<string, string>();
foreach (IDBTable tb in DbSet)
{
ddls.Add(tb.TableName, tb.DDL);
}
bool isVaild = sqliteHelper.IsTableValid(ddls);
if (!isVaild)
{
Rebuild();
}
else
{
//加载
Load();
}
return isVaild;
}
}
}
......@@ -48,6 +48,7 @@
<Compile Include="IDBTable.cs" />
<Compile Include="IgnoreAttribute.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SQLiteDbContext.cs" />
<Compile Include="SQLiteHelper.cs" />
</ItemGroup>
<ItemGroup>
......
using SQLite;
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UnitTestProject1.Model
{
public class DBModel: SQLiteDbContext
{
public DBTable<User> Users { get; set; } = new DBTable<User>();
public DBTable<Book> Books { get; set; } = new DBTable<Book>();
public DBModel()
{
}
}
}
using SQLite;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UnitTestProject1.Model
{
[Table("book")]
public class Book
{
[Key]
[PropertyIndex(0)]
public Int64 ID { get; set; }
/// <summary>
/// 书名
/// </summary>
[PropertyIndex(1)]
public string BookName { get; set; }
/// <summary>
/// 页数
/// </summary>
[PropertyIndex(2)]
public int PageCount { get; set; }
/// <summary>
/// 印刷日期
/// </summary>
[PropertyIndex(3)]
public DateTime PrintTime { get; set; }
}
public class Book2
{
[Key]
[PropertyIndex(0)]
public Int64 ID { get; set; }
/// <summary>
/// 书名
/// </summary>
[PropertyIndex(1)]
public string BookName { get; set; }
/// <summary>
/// 页数
/// </summary>
[PropertyIndex(2)]
public long PageCount { get; set; }
/// <summary>
/// 印刷日期
/// </summary>
public DateTime PrintTime { get; set; }
}
[Table("user")]
public class User
{
[Key]
[PropertyIndex(0)]
public Int64 ID { get; set; }
/// <summary>
/// 姓名
/// </summary>
[PropertyIndex(1)]
public string Name { get; set; }
/// <summary>
/// 拥有的书的ID
/// </summary>
[PropertyIndex(2)]
public string BookIDs { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UnitTestProject1.Model
{
public class UserLC
{
public long ID { get; set; }
public string Name { get; set; }
public List<long> BookIDs { get; set; }
}
/// <summary>
/// LC 与 DB 类的映射关系, 会在程序入口处, 手动使用
/// var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
/// var cfg = new MapperConfigurationExpression();
/// cfg.AddMaps(assemblies);
/// Mapper.Initialize(cfg);
///
/// 枚举全部程序集 中的AutoMapper.Profile 全部加载!!!
/// </summary>
public class LC_AutoMapperProfile : AutoMapper.Profile
{
public LC_AutoMapperProfile()
{
#region LC_CoatingWidthData
CreateMap<UserLC, User>()
.ForMember(s => s.BookIDs, opt =>{
opt.MapFrom(s => Newtonsoft.Json.JsonConvert.SerializeObject(s.BookIDs));
})
.ReverseMap()
.ForMember(s => s.BookIDs, opt =>{
opt.MapFrom(s => Newtonsoft.Json.JsonConvert.DeserializeObject<List<long>>(s.BookIDs));
});
#endregion
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("UnitTestProject1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UnitTestProject1")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("6f59f24f-4cbe-426b-afd7-3174de4ca263")]
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using AutoMapper.Data;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SQLite;
namespace UnitTestProject1
{
[TestClass]
public class UnitTestSQLiteHelper
{
[TestMethod]
public void TestMethodSave()
{
Exception ex = null;
try
{
var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();
cfg.AddProfiles("UnitTestProject1");
AutoMapper.Mapper.Initialize(cfg);
Model.DBModel dBModel = new Model.DBModel();
dBModel.Init();
var books_db = new List<Model.Book>
{
new Model.Book()
{
ID = dBModel.IDs[dBModel.Books]++,
BookName = "ASP.NET MVC 5 高级编程(第5版)",
PageCount = 460,
PrintTime = new DateTime(2019,8,8)
},
new Model.Book()
{
ID = dBModel.IDs[dBModel.Books]++,
BookName = "c# 入门经典(第7版)",
PageCount = 432,
PrintTime = new DateTime(2012,5,20)
},
};
var users_lc = new List<Model.UserLC>
{
new Model.UserLC(){
ID = dBModel.IDs[dBModel.Users]++,
Name = "潘栩锋",
BookIDs = new List<long>{
books_db[0].ID,books_db[1].ID
}
}
};
var users_db = AutoMapper.Mapper.Map<List<Model.User>>(users_lc);
List<string> sqls = new List<string>();
foreach (var book_db in books_db)
sqls.Add(SQLiteHelper.GetInsertCommandText(book_db));
foreach (var user_db in users_db)
sqls.Add(SQLiteHelper.GetInsertCommandText(user_db));
dBModel.sqliteHelper.QueryTranAsync(sqls);
}
catch (Exception e)
{
ex = e;
}
Assert.IsNull(ex);
}
[TestMethod]
public void TestMethodLoad()
{
Exception ex = null;
try
{
//var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();
cfg.AddDataReaderMapping();
cfg.AddProfiles("UnitTestProject1");
AutoMapper.Mapper.Initialize(cfg);
Model.DBModel dBModel = new Model.DBModel();
dBModel.Init();
string sql =
$"SELECT * FROM {dBModel.Users.TableName}" +
$" ORDER BY ID";
var table = dBModel.sqliteHelper.ExecuteReader(sql);
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
var users_db = SQLiteHelper.ToObjs<Model.User>(table);
stopwatch.Stop();
Console.WriteLine($"SQLiteHelper.ToObjs<Model.User>(table) Elapsed={stopwatch.ElapsedMilliseconds}ms");
stopwatch.Restart();
var users_db2 = AutoMapper.Mapper.Map<IDataReader,List<Model.User>>(table.CreateDataReader());
stopwatch.Stop();
Console.WriteLine($"AutoMapper.Mapper.Map<IDataReader,List<Model.User>>(table.CreateDataReader()) Elapsed={stopwatch.ElapsedMilliseconds}ms");
var users_lc = AutoMapper.Mapper.Map<List<Model.UserLC>>(users_db);
sql =
$"SELECT * FROM {dBModel.Books.TableName}" +
$" ORDER BY ID";
table = dBModel.sqliteHelper.ExecuteReader(sql);
stopwatch.Restart();
var books_db = SQLiteHelper.ToObjs<Model.Book>(table);
stopwatch.Stop();
Console.WriteLine($"SQLiteHelper.ToObjs<Model.Book>(table) Elapsed={stopwatch.ElapsedMilliseconds}ms");
stopwatch.Restart();
var books_db2 = AutoMapper.Mapper.Map<IDataReader, List<Model.Book2>>(table.CreateDataReader());
stopwatch.Stop();
Console.WriteLine($"AutoMapper.Mapper.Map<IDataReader, List<Model.Book2>>(table.CreateDataReader()) Elapsed={stopwatch.ElapsedMilliseconds}ms");
string json = Newtonsoft.Json.JsonConvert.SerializeObject(books_db, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
}
catch (Exception e)
{
ex = e;
Assert.Fail(e.Message);
}
Assert.IsNull(ex);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{6F59F24F-4CBE-426B-AFD7-3174DE4CA263}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>UnitTestProject1</RootNamespace>
<AssemblyName>UnitTestProject1</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
</ItemGroup>
<ItemGroup>
<Compile Include="Model\DBModel.cs" />
<Compile Include="Model\DBTable.cs" />
<Compile Include="Model\LCTable.cs" />
<Compile Include="UnitTest1.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoMapper">
<Version>8.0.0</Version>
</PackageReference>
<PackageReference Include="AutoMapper.Data">
<Version>3.0.0</Version>
</PackageReference>
<PackageReference Include="MSTest.TestAdapter">
<Version>1.3.2</Version>
</PackageReference>
<PackageReference Include="MSTest.TestFramework">
<Version>1.3.2</Version>
</PackageReference>
<PackageReference Include="System.Data.SQLite">
<Version>1.0.111</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SQLiteHelper\SQLiteHelper.csproj">
<Project>{4cbabfaa-1c62-4510-ac63-a51ee5fd50ff}</Project>
<Name>SQLiteHelper</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment