源代码改用vs默认格式化

This commit is contained in:
28810 2019-06-27 09:40:35 +08:00
parent 873364c7ee
commit f8c3608fda
309 changed files with 73814 additions and 67594 deletions

View File

@ -8,207 +8,230 @@ using BenchmarkDotNet.Running;
using Microsoft.EntityFrameworkCore;
//using SqlSugar;
namespace FreeSql.Bechmarker {
namespace FreeSql.Bechmarker
{
public class Program {
public static void Main(string[] args) {
var summaryInsert = BenchmarkRunner.Run<OrmVsInsert>();
var summarySelect = BenchmarkRunner.Run<OrmVsSelect>();
var summaryUpdate = BenchmarkRunner.Run<OrmVsUpdate>();
}
}
public class Program
{
public static void Main(string[] args)
{
var summaryInsert = BenchmarkRunner.Run<OrmVsInsert>();
var summarySelect = BenchmarkRunner.Run<OrmVsSelect>();
var summaryUpdate = BenchmarkRunner.Run<OrmVsUpdate>();
}
}
public class Orm {
public static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=20")
//.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=20")
.UseAutoSyncStructure(false)
.UseNoneCommandParameter(true)
//.UseConfigEntityFromDbFirst(true)
.Build();
public class Orm
{
public static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=20")
//.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=20")
.UseAutoSyncStructure(false)
.UseNoneCommandParameter(true)
//.UseConfigEntityFromDbFirst(true)
.Build();
//public static SqlSugarClient sugar {
// get => new SqlSugarClient(new ConnectionConfig() {
// //不欺负让连接池100个最小
// ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20",
// DbType = DbType.SqlServer,
// //ConnectionString = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=20;Max Pool Size=20",
// //DbType = DbType.MySql,
// IsAutoCloseConnection = true,
// InitKeyType = InitKeyType.Attribute
// });
//}
}
class SongContext : DbContext {
public DbSet<Song> Songs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
optionsBuilder.UseSqlServer(@"Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=21;Max Pool Size=21");
//optionsBuilder.UseMySql("Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=21;Max Pool Size=21");
}
}
//public static SqlSugarClient sugar {
// get => new SqlSugarClient(new ConnectionConfig() {
// //不欺负让连接池100个最小
// ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20",
// DbType = DbType.SqlServer,
// //ConnectionString = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=20;Max Pool Size=20",
// //DbType = DbType.MySql,
// IsAutoCloseConnection = true,
// InitKeyType = InitKeyType.Attribute
// });
//}
}
class SongContext : DbContext
{
public DbSet<Song> Songs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=21;Max Pool Size=21");
//optionsBuilder.UseMySql("Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=21;Max Pool Size=21");
}
}
[CoreJob]
[RPlotExporter, RankColumn]
public class OrmVsInsert {
public IEnumerable<Song> songs;
[CoreJob]
[RPlotExporter, RankColumn]
public class OrmVsInsert
{
public IEnumerable<Song> songs;
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
public int size;
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
public int size;
[GlobalSetup]
public void Setup() {
Orm.fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag));
//Orm.sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag));
//sugar创建表失败SqlSugar.SqlSugarException: Sequence contains no elements
[GlobalSetup]
public void Setup()
{
Orm.fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag));
//Orm.sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag));
//sugar创建表失败SqlSugar.SqlSugarException: Sequence contains no elements
//测试前清空数据
Orm.fsql.Delete<Song>().Where(a => a.Id > 0).ExecuteAffrows();
//Orm.sugar.Deleteable<Song>().Where(a => a.Id > 0).ExecuteCommand();
Orm.fsql.Ado.ExecuteNonQuery("delete from efcore_song");
//测试前清空数据
Orm.fsql.Delete<Song>().Where(a => a.Id > 0).ExecuteAffrows();
//Orm.sugar.Deleteable<Song>().Where(a => a.Id > 0).ExecuteCommand();
Orm.fsql.Ado.ExecuteNonQuery("delete from efcore_song");
songs = Enumerable.Range(0, size).Select(a => new Song {
Create_time = DateTime.Now,
Is_deleted = false,
Title = $"Insert_{a}",
Url = $"Url_{a}"
});
songs = Enumerable.Range(0, size).Select(a => new Song
{
Create_time = DateTime.Now,
Is_deleted = false,
Title = $"Insert_{a}",
Url = $"Url_{a}"
});
//预热
Orm.fsql.Insert(songs.First()).ExecuteAffrows();
//Orm.sugar.Insertable(songs.First()).ExecuteCommand();
using (var db = new SongContext()) {
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.AddRange(songs.First());
db.SaveChanges();
}
}
//预热
Orm.fsql.Insert(songs.First()).ExecuteAffrows();
//Orm.sugar.Insertable(songs.First()).ExecuteCommand();
using (var db = new SongContext())
{
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.AddRange(songs.First());
db.SaveChanges();
}
}
[Benchmark]
public int FreeSqlInsert() => Orm.fsql.Insert(songs).ExecuteAffrows();
[Benchmark]
public int FreeSqlInsert() => Orm.fsql.Insert(songs).ExecuteAffrows();
//[Benchmark]
//public int SqlSugarInsert() => Orm.sugar.Insertable(songs.ToArray()).ExecuteCommand();
//[Benchmark]
//public int SqlSugarInsert() => Orm.sugar.Insertable(songs.ToArray()).ExecuteCommand();
[Benchmark]
public int EfCoreInsert() {
using (var db = new SongContext()) {
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.AddRange(songs.ToArray());
return db.SaveChanges();
}
}
}
[Benchmark]
public int EfCoreInsert()
{
using (var db = new SongContext())
{
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.AddRange(songs.ToArray());
return db.SaveChanges();
}
}
}
[CoreJob]
[RPlotExporter, RankColumn]
public class OrmVsUpdate {
public List<Song> songs;
[CoreJob]
[RPlotExporter, RankColumn]
public class OrmVsUpdate
{
public List<Song> songs;
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
public int size;
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
public int size;
[GlobalSetup]
public void Setup() {
songs = Orm.fsql.Select<Song>().Limit(size).ToList();
}
[GlobalSetup]
public void Setup()
{
songs = Orm.fsql.Select<Song>().Limit(size).ToList();
}
[Benchmark]
public int FreeSqlUpdate() => Orm.fsql.Update<Song>().SetSource(songs).ExecuteAffrows();
[Benchmark]
public int FreeSqlUpdate() => Orm.fsql.Update<Song>().SetSource(songs).ExecuteAffrows();
//[Benchmark]
//public int SqlSugarUpdate() => Orm.sugar.Updateable(songs).ExecuteCommand();
//[Benchmark]
//public int SqlSugarUpdate() => Orm.sugar.Updateable(songs).ExecuteCommand();
[Benchmark]
public int EfCoreUpdate() {
using (var db = new SongContext()) {
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.UpdateRange(songs.ToArray());
return db.SaveChanges();
}
}
}
[Benchmark]
public int EfCoreUpdate()
{
using (var db = new SongContext())
{
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.UpdateRange(songs.ToArray());
return db.SaveChanges();
}
}
}
[CoreJob]
[RPlotExporter, RankColumn]
public class OrmVsSelect {
[CoreJob]
[RPlotExporter, RankColumn]
public class OrmVsSelect
{
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
public int size;
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
public int size;
[GlobalSetup]
public void Setup() {
}
[GlobalSetup]
public void Setup()
{
[Benchmark]
public List<Song> FreeSqlSelect() => Orm.fsql.Select<Song>().Limit(size).ToList();
}
//[Benchmark]
//public List<Song> SqlSugarSelect() => Orm.sugar.Queryable<Song>().Take(size).ToList();
[Benchmark]
public List<Song> FreeSqlSelect() => Orm.fsql.Select<Song>().Limit(size).ToList();
[Benchmark]
public List<Song> EfCoreSelect() {
using (var db = new SongContext()) {
return db.Songs.Take(size).AsNoTracking().ToList();
}
}
}
//[Benchmark]
//public List<Song> SqlSugarSelect() => Orm.sugar.Queryable<Song>().Take(size).ToList();
[FreeSql.DataAnnotations.Table(Name = "freesql_song")]
//[SugarTable("sugar_song")]
[Table("efcore_song")]
public class Song {
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
//[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime? Create_time { get; set; }
public bool? Is_deleted { get; set; }
public string Title { get; set; }
public string Url { get; set; }
[Benchmark]
public List<Song> EfCoreSelect()
{
using (var db = new SongContext())
{
return db.Songs.Take(size).AsNoTracking().ToList();
}
}
}
//[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual ICollection<Tag> Tags { get; set; }
}
[FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")]
//[SugarTable("sugar_song_tag")]
[Table("efcore_song_tag")]
public class Song_tag {
public int Song_id { get; set; }
//[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual Song Song { get; set; }
[FreeSql.DataAnnotations.Table(Name = "freesql_song")]
//[SugarTable("sugar_song")]
[Table("efcore_song")]
public class Song
{
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
//[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime? Create_time { get; set; }
public bool? Is_deleted { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public int Tag_id { get; set; }
//[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual Tag Tag { get; set; }
}
[FreeSql.DataAnnotations.Table(Name = "freesql_tag")]
//[SugarTable("sugar_tag")]
[Table("efcore_tag")]
public class Tag {
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
//[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? Parent_id { get; set; }
//[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual Tag Parent { get; set; }
//[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual ICollection<Tag> Tags { get; set; }
}
[FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")]
//[SugarTable("sugar_song_tag")]
[Table("efcore_song_tag")]
public class Song_tag
{
public int Song_id { get; set; }
//[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual Song Song { get; set; }
public decimal? Ddd { get; set; }
public string Name { get; set; }
public int Tag_id { get; set; }
//[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual Tag Tag { get; set; }
}
[FreeSql.DataAnnotations.Table(Name = "freesql_tag")]
//[SugarTable("sugar_tag")]
[Table("efcore_tag")]
public class Tag
{
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
//[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? Parent_id { get; set; }
//[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual Tag Parent { get; set; }
//[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual ICollection<Song> Songs { get; set; }
//[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual ICollection<Tag> Tags { get; set; }
}
public decimal? Ddd { get; set; }
public string Name { get; set; }
//[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual ICollection<Song> Songs { get; set; }
//[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual ICollection<Tag> Tags { get; set; }
}
}

View File

@ -5,237 +5,251 @@ using System.Threading.Tasks;
using FreeSql;
using Microsoft.AspNetCore.Mvc;
namespace dbcontext_01.Controllers {
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase {
IFreeSql _orm;
SongContext _songContext;
public ValuesController(SongContext songContext,
IFreeSql orm1, IFreeSql orm2,
IFreeSql<long> orm3
) {
_songContext = songContext;
_orm = orm1;
namespace dbcontext_01.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
IFreeSql _orm;
SongContext _songContext;
public ValuesController(SongContext songContext,
IFreeSql orm1, IFreeSql orm2,
IFreeSql<long> orm3
)
{
_songContext = songContext;
_orm = orm1;
}
// GET api/values
[HttpGet]
async public Task<string> Get()
{
long id = 0;
try
{
var repos2Song = _orm.GetRepository<Song, int>();
repos2Song.Where(a => a.Id > 10).ToList();
//查询结果,进入 states
var song = new Song { };
repos2Song.Insert(song);
id = song.Id;
}
// GET api/values
[HttpGet]
async public Task<string> Get() {
var adds = Enumerable.Range(0, 100)
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
.ToList();
//创建一堆无主键值
long id = 0;
repos2Song.Insert(adds);
try {
for (var a = 0; a < 10; a++)
adds[a].Title = "dkdkdkdk" + a;
var repos2Song = _orm.GetRepository<Song, int>();
repos2Song.Where(a => a.Id > 10).ToList();
//查询结果,进入 states
repos2Song.Update(adds);
//批量修改
var song = new Song { };
repos2Song.Insert(song);
id = song.Id;
repos2Song.Delete(adds.Skip(10).Take(20).ToList());
//批量删除10-20 元素的主键值会被清除
var adds = Enumerable.Range(0, 100)
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
.ToList();
//创建一堆无主键值
adds.Last().Url = "skldfjlksdjglkjjcccc";
repos2Song.Update(adds.Last());
repos2Song.Insert(adds);
adds.First().Url = "skldfjlksdjglkjjcccc";
repos2Song.Update(adds.First());
for (var a = 0; a < 10; a++)
adds[a].Title = "dkdkdkdk" + a;
repos2Song.Update(adds);
//批量修改
var ctx = _songContext;
var tag = new Tag
{
Name = "testaddsublist",
Tags = new[] {
new Tag { Name = "sub1" },
new Tag { Name = "sub2" },
new Tag {
Name = "sub3",
Tags = new[] {
new Tag { Name = "sub3_01" }
}
}
}
};
ctx.Tags.Add(tag);
repos2Song.Delete(adds.Skip(10).Take(20).ToList());
//批量删除10-20 元素的主键值会被清除
adds.Last().Url = "skldfjlksdjglkjjcccc";
repos2Song.Update(adds.Last());
ctx.UnitOfWork.GetOrBeginTransaction();
adds.First().Url = "skldfjlksdjglkjjcccc";
repos2Song.Update(adds.First());
var tagAsync = new Tag
{
Name = "testaddsublist",
Tags = new[] {
new Tag { Name = "sub1" },
new Tag { Name = "sub2" },
new Tag {
Name = "sub3",
Tags = new[] {
new Tag { Name = "sub3_01" }
}
}
}
};
await ctx.Tags.AddAsync(tagAsync);
var ctx = _songContext;
var tag = new Tag {
Name = "testaddsublist",
Tags = new[] {
new Tag { Name = "sub1" },
new Tag { Name = "sub2" },
new Tag {
Name = "sub3",
Tags = new[] {
new Tag { Name = "sub3_01" }
}
}
}
};
ctx.Tags.Add(tag);
ctx.Songs.Select.Where(a => a.Id > 10).ToList();
//查询结果,进入 states
song = new Song { };
//可插入的 song
ctx.UnitOfWork.GetOrBeginTransaction();
ctx.Songs.Add(song);
id = song.Id;
//因有自增类型立即开启事务执行SQL返回自增值
var tagAsync = new Tag {
Name = "testaddsublist",
Tags = new[] {
new Tag { Name = "sub1" },
new Tag { Name = "sub2" },
new Tag {
Name = "sub3",
Tags = new[] {
new Tag { Name = "sub3_01" }
}
}
}
};
await ctx.Tags.AddAsync(tagAsync);
adds = Enumerable.Range(0, 100)
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
.ToList();
//创建一堆无主键值
ctx.Songs.AddRange(adds);
//立即执行,将自增值赋给 adds 所有元素,因为有自增类型,如果其他类型,指定传入主键值,不会立即执行
ctx.Songs.Select.Where(a => a.Id > 10).ToList();
//查询结果,进入 states
for (var a = 0; a < 10; a++)
adds[a].Title = "dkdkdkdk" + a;
song = new Song { };
//可插入的 song
ctx.Songs.UpdateRange(adds);
//批量修改,进入队列
ctx.Songs.Add(song);
id = song.Id;
//因有自增类型立即开启事务执行SQL返回自增值
ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList());
//批量删除,进入队列,完成时 10-20 元素的主键值会被清除
adds = Enumerable.Range(0, 100)
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
.ToList();
//创建一堆无主键值
//ctx.Songs.Update(adds.First());
ctx.Songs.AddRange(adds);
//立即执行,将自增值赋给 adds 所有元素,因为有自增类型,如果其他类型,指定传入主键值,不会立即执行
adds.Last().Url = "skldfjlksdjglkjjcccc";
ctx.Songs.Update(adds.Last());
for (var a = 0; a < 10; a++)
adds[a].Title = "dkdkdkdk" + a;
adds.First().Url = "skldfjlksdjglkjjcccc";
ctx.Songs.Update(adds.First());
ctx.Songs.UpdateRange(adds);
//批量修改,进入队列
//单条修改 urls 的值,进入队列
ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList());
//批量删除,进入队列,完成时 10-20 元素的主键值会被清除
//throw new Exception("回滚");
//ctx.Songs.Update(adds.First());
//ctx.Songs.Select.First();
//这里做一个查询,会立即打包【执行队列】,避免没有提交的数据,影响查询结果
adds.Last().Url = "skldfjlksdjglkjjcccc";
ctx.Songs.Update(adds.Last());
ctx.SaveChanges();
//打包【执行队列】,提交事务
adds.First().Url = "skldfjlksdjglkjjcccc";
ctx.Songs.Update(adds.First());
//单条修改 urls 的值,进入队列
using (var uow = _orm.CreateUnitOfWork())
{
//throw new Exception("回滚");
var reposSong = uow.GetRepository<Song, int>();
reposSong.Where(a => a.Id > 10).ToList();
//查询结果,进入 states
//ctx.Songs.Select.First();
//这里做一个查询,会立即打包【执行队列】,避免没有提交的数据,影响查询结果
song = new Song { };
reposSong.Insert(song);
id = song.Id;
ctx.SaveChanges();
//打包【执行队列】,提交事务
adds = Enumerable.Range(0, 100)
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
.ToList();
//创建一堆无主键值
reposSong.Insert(adds);
using (var uow = _orm.CreateUnitOfWork()) {
for (var a = 0; a < 10; a++)
adds[a].Title = "dkdkdkdk" + a;
var reposSong = uow.GetRepository<Song, int>();
reposSong.Where(a => a.Id > 10).ToList();
//查询结果,进入 states
reposSong.Update(adds);
//批量修改
song = new Song { };
reposSong.Insert(song);
id = song.Id;
reposSong.Delete(adds.Skip(10).Take(20).ToList());
//批量删除10-20 元素的主键值会被清除
adds = Enumerable.Range(0, 100)
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
.ToList();
//创建一堆无主键值
adds.Last().Url = "skldfjlksdjglkjjcccc";
reposSong.Update(adds.Last());
reposSong.Insert(adds);
adds.First().Url = "skldfjlksdjglkjjcccc";
reposSong.Update(adds.First());
for (var a = 0; a < 10; a++)
adds[a].Title = "dkdkdkdk" + a;
uow.Commit();
}
reposSong.Update(adds);
//批量修改
reposSong.Delete(adds.Skip(10).Take(20).ToList());
//批量删除10-20 元素的主键值会被清除
adds.Last().Url = "skldfjlksdjglkjjcccc";
reposSong.Update(adds.Last());
//using (var ctx = new SongContext()) {
adds.First().Url = "skldfjlksdjglkjjcccc";
reposSong.Update(adds.First());
// var song = new Song { };
// await ctx.Songs.AddAsync(song);
// id = song.Id;
uow.Commit();
}
// var adds = Enumerable.Range(0, 100)
// .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
// .ToList();
// await ctx.Songs.AddRangeAsync(adds);
// for (var a = 0; a < adds.Count; a++)
// adds[a].Title = "dkdkdkdk" + a;
// ctx.Songs.UpdateRange(adds);
//using (var ctx = new SongContext()) {
// ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList());
// var song = new Song { };
// await ctx.Songs.AddAsync(song);
// id = song.Id;
// //ctx.Songs.Update(adds.First());
// var adds = Enumerable.Range(0, 100)
// .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
// .ToList();
// await ctx.Songs.AddRangeAsync(adds);
// adds.Last().Url = "skldfjlksdjglkjjcccc";
// ctx.Songs.Update(adds.Last());
// for (var a = 0; a < adds.Count; a++)
// adds[a].Title = "dkdkdkdk" + a;
// //throw new Exception("回滚");
// ctx.Songs.UpdateRange(adds);
// await ctx.SaveChangesAsync();
//}
}
catch
{
var item = await _orm.Select<Song>().Where(a => a.Id == id).FirstAsync();
// ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList());
throw;
}
// //ctx.Songs.Update(adds.First());
var item22 = await _orm.Select<Song>().Where(a => a.Id == id).FirstAsync();
var item33 = await _orm.Select<Song>().Where(a => a.Id > id).ToListAsync();
// adds.Last().Url = "skldfjlksdjglkjjcccc";
// ctx.Songs.Update(adds.Last());
return item22.Id.ToString();
}
// //throw new Exception("回滚");
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}
// await ctx.SaveChangesAsync();
//}
} catch {
var item = await _orm.Select<Song>().Where(a => a.Id == id).FirstAsync();
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
throw;
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
var item22 = await _orm.Select<Song>().Where(a => a.Id == id).FirstAsync();
var item33 = await _orm.Select<Song>().Where(a => a.Id > id).ToListAsync();
return item22.Id.ToString();
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id) {
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value) {
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value) {
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id) {
}
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}

View File

@ -3,50 +3,55 @@ using FreeSql.DataAnnotations;
using System;
using System.Collections.Generic;
namespace dbcontext_01 {
namespace dbcontext_01
{
public class SongContext : DbContext {
public class SongContext : DbContext
{
public DbSet<Song> Songs { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<Song> Songs { get; set; }
public DbSet<Tag> Tags { get; set; }
//protected override void OnConfiguring(DbContextOptionsBuilder builder) {
// builder.UseFreeSql(dbcontext_01.Startup.Fsql);
//}
}
//protected override void OnConfiguring(DbContextOptionsBuilder builder) {
// builder.UseFreeSql(dbcontext_01.Startup.Fsql);
//}
}
public class Song {
[Column(IsIdentity = true)]
public int Id { get; set; }
public DateTime? Create_time { get; set; }
public bool? Is_deleted { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public class Song
{
[Column(IsIdentity = true)]
public int Id { get; set; }
public DateTime? Create_time { get; set; }
public bool? Is_deleted { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
[Column(IsVersion = true)]
public long versionRow { get; set; }
}
public class Song_tag {
public int Song_id { get; set; }
public virtual Song Song { get; set; }
[Column(IsVersion = true)]
public long versionRow { get; set; }
}
public class Song_tag
{
public int Song_id { get; set; }
public virtual Song Song { get; set; }
public int Tag_id { get; set; }
public virtual Tag Tag { get; set; }
}
public int Tag_id { get; set; }
public virtual Tag Tag { get; set; }
}
public class Tag {
[Column(IsIdentity = true)]
public int Id { get; set; }
public int? Parent_id { get; set; }
public virtual Tag Parent { get; set; }
public class Tag
{
[Column(IsIdentity = true)]
public int Id { get; set; }
public int? Parent_id { get; set; }
public virtual Tag Parent { get; set; }
public decimal? Ddd { get; set; }
public string Name { get; set; }
public decimal? Ddd { get; set; }
public string Name { get; set; }
public virtual ICollection<Song> Songs { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public virtual ICollection<Song> Songs { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
}

View File

@ -17,51 +17,56 @@ namespace dbcontext_01
public class Program
{
public class Song {
[Column(IsIdentity = true)]
public int Id { get; set; }
public string BigNumber { get; set; }
public class Song
{
[Column(IsIdentity = true)]
public int Id { get; set; }
public string BigNumber { get; set; }
[Column(IsVersion = true)]//使用简单
public long versionRow { get; set; }
}
[Column(IsVersion = true)]//使用简单
public long versionRow { get; set; }
}
public class SongContext : DbContext {
public class SongContext : DbContext
{
public DbSet<Song> Songs { get; set; }
public DbSet<Song> Songs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder builder) {
builder.UseFreeSql(fsql);
}
}
static IFreeSql fsql;
public static void Main(string[] args) {
fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\dd2.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
.UseNoneCommandParameter(true)
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseFreeSql(fsql);
}
}
static IFreeSql fsql;
public static void Main(string[] args)
{
fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\dd2.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
.UseNoneCommandParameter(true)
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
.Build();
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
.Build();
using (var ctx = new SongContext()) {
var song = new Song { BigNumber = "1000000000000000000" };
ctx.Songs.Add(song);
using (var ctx = new SongContext())
{
var song = new Song { BigNumber = "1000000000000000000" };
ctx.Songs.Add(song);
ctx.Songs.Update(song);
ctx.Songs.Update(song);
song.BigNumber = (BigInteger.Parse(song.BigNumber) + 1).ToString();
ctx.Songs.Update(song);
song.BigNumber = (BigInteger.Parse(song.BigNumber) + 1).ToString();
ctx.Songs.Update(song);
ctx.SaveChanges();
ctx.SaveChanges();
var sql = fsql.Update<Song>().SetSource(song).ToSql();
}
var sql = fsql.Update<Song>().SetSource(song).ToSql();
}
CreateWebHostBuilder(args).Build().Run();
}
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)

View File

@ -1,27 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:53030/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:53030/",
"sslPort": 0
}
},
"dbcontext_01": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:53031/"
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"dbcontext_01": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:53031/"
}
}
}
}

View File

@ -19,93 +19,101 @@ namespace dbcontext_01
{
Configuration = configuration;
Fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document2.db;Pooling=true;Max Pool Size=10")
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
Fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document2.db;Pooling=true;Max Pool Size=10")
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
//.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10")
//.UseSyncStructureToUpper(true)
//.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10")
//.UseSyncStructureToUpper(true)
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
.UseNoneCommandParameter(true)
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
.UseNoneCommandParameter(true)
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText),
(cmd, log) => Trace.WriteLine(log)
)
.Build();
Fsql.Aop.SyncStructureBefore = (s, e) => {
Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName)));
};
Fsql.Aop.SyncStructureAfter = (s, e) => {
Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName)) + " " + e.ElapsedMilliseconds + "ms\r\n" + e.Exception?.Message + e.Sql);
};
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText),
(cmd, log) => Trace.WriteLine(log)
)
.Build();
Fsql.Aop.SyncStructureBefore = (s, e) =>
{
Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName)));
};
Fsql.Aop.SyncStructureAfter = (s, e) =>
{
Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName)) + " " + e.ElapsedMilliseconds + "ms\r\n" + e.Exception?.Message + e.Sql);
};
Fsql.Aop.CurdBefore = (s, e) => {
Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + ", " + e.Sql);
};
Fsql.Aop.CurdAfter = (s, e) => {
Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + " " + e.ElapsedMilliseconds + "ms, " + e.Sql);
};
Fsql.Aop.CurdBefore = (s, e) =>
{
Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + ", " + e.Sql);
};
Fsql.Aop.CurdAfter = (s, e) =>
{
Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + " " + e.ElapsedMilliseconds + "ms, " + e.Sql);
};
Fsql2 = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document222.db;Pooling=true;Max Pool Size=10")
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
Fsql2 = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document222.db;Pooling=true;Max Pool Size=10")
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText),
(cmd, log) => Trace.WriteLine(log)
)
.Build<long>();
}
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText),
(cmd, log) => Trace.WriteLine(log)
)
.Build<long>();
}
enum MySql { }
enum PgSql { }
enum MySql { }
enum PgSql { }
public IConfiguration Configuration { get; }
public static IFreeSql Fsql { get; private set; }
public static IFreeSql<long> Fsql2 { get; private set; }
public IConfiguration Configuration { get; }
public static IFreeSql Fsql { get; private set; }
public static IFreeSql<long> Fsql2 { get; private set; }
public void ConfigureServices(IServiceCollection services)
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwaggerGen(options => {
options.SwaggerDoc("v1", new Info {
Version = "v1",
Title = "FreeSql.DbContext API"
});
//options.IncludeXmlComments(xmlPath);
});
services.AddMvc();
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "FreeSql.DbContext API"
});
//options.IncludeXmlComments(xmlPath);
});
services.AddSingleton<IFreeSql>(Fsql);
services.AddSingleton<IFreeSql<long>>(Fsql2);
services.AddFreeDbContext<SongContext>(options => options.UseFreeSql(Fsql));
services.AddSingleton<IFreeSql>(Fsql);
services.AddSingleton<IFreeSql<long>>(Fsql2);
services.AddFreeDbContext<SongContext>(options => options.UseFreeSql(Fsql));
var sql1 = Fsql.Update<Song>(1).Set(a => a.Id + 10).ToSql();
var sql2 = Fsql.Update<Song>(1).Set(a => a.Title + 10).ToSql();
var sql3 = Fsql.Update<Song>(1).Set(a => a.Create_time.Value.AddHours(1)).ToSql();
}
var sql1 = Fsql.Update<Song>(1).Set(a => a.Id + 10).ToSql();
var sql2 = Fsql.Update<Song>(1).Set(a => a.Title + 10).ToSql();
var sql3 = Fsql.Update<Song>(1).Set(a => a.Create_time.Value.AddHours(1)).ToSql();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
Console.InputEncoding = Encoding.GetEncoding("GB2312");
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
Console.InputEncoding = Encoding.GetEncoding("GB2312");
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
app.UseDeveloperExceptionPage();
app.UseMvc();
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
app.UseDeveloperExceptionPage();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
});
}
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
});
}
}
}

View File

@ -1,9 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
}

View File

@ -1,8 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@ -2,18 +2,22 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
namespace efcore_to_freesql.DBContexts {
namespace efcore_to_freesql.DBContexts
{
public class BaseDBContext : DbContext {
public class BaseDBContext : DbContext
{
public static IFreeSql Fsql { get; set; }
public static IFreeSql Fsql { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
Fsql.CodeFirst.ConfigEntity(modelBuilder.Model); //ͬ²½ÅäÖÃ
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
optionsBuilder.UseSqlite(@"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
Fsql.CodeFirst.ConfigEntity(modelBuilder.Model); //ͬ²½ÅäÖÃ
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(@"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10");
}
}
}

View File

@ -1,18 +1,21 @@
using efcore_to_freesql.Entitys;
using Microsoft.EntityFrameworkCore;
namespace efcore_to_freesql.DBContexts {
namespace efcore_to_freesql.DBContexts
{
public class Topic1Context : BaseDBContext {
public class Topic1Context : BaseDBContext
{
public DbSet<Topic1> Topic1s { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Topic1>().ToTable("topic1_sss").HasKey(a => a.Id);
modelBuilder.Entity<Topic1>().Property(a => a.Id).HasColumnName("topic1_id").ValueGeneratedOnAdd();
modelBuilder.Entity<Topic1>().ToTable("topic1_sss").HasKey(a => a.Id);
modelBuilder.Entity<Topic1>().Property(a => a.Id).HasColumnName("topic1_id").ValueGeneratedOnAdd();
base.OnModelCreating(modelBuilder);
}
}
base.OnModelCreating(modelBuilder);
}
}
}

View File

@ -1,18 +1,21 @@
using efcore_to_freesql.Entitys;
using Microsoft.EntityFrameworkCore;
namespace efcore_to_freesql.DBContexts {
namespace efcore_to_freesql.DBContexts
{
public class Topic2Context : BaseDBContext {
public class Topic2Context : BaseDBContext
{
public DbSet<Topic2> Topic2s { get; set; }
public DbSet<Topic2> Topic2s { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Topic2>().ToTable("topic2_sss");
modelBuilder.Entity<Topic2>().Property(a => a.Id).HasColumnName("topic2_id");
modelBuilder.Entity<Topic2>().ToTable("topic2_sss");
modelBuilder.Entity<Topic2>().Property(a => a.Id).HasColumnName("topic2_id");
base.OnModelCreating(modelBuilder);
}
}
base.OnModelCreating(modelBuilder);
}
}
}

View File

@ -1,6 +1,7 @@
using System;
namespace efcore_to_freesql.Entitys {
namespace efcore_to_freesql.Entitys
{
public class Topic1
{

View File

@ -2,7 +2,8 @@ using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace efcore_to_freesql.Entitys {
namespace efcore_to_freesql.Entitys
{
public class Topic2
{

View File

@ -6,60 +6,67 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public static class CodeFirstExtensions {
public static class CodeFirstExtensions
{
public static void ConfigEntity(this ICodeFirst codeFirst, IModel efmodel) {
public static void ConfigEntity(this ICodeFirst codeFirst, IModel efmodel)
{
foreach (var type in efmodel.GetEntityTypes()) {
foreach (var type in efmodel.GetEntityTypes())
{
codeFirst.ConfigEntity(type.ClrType, a => {
codeFirst.ConfigEntity(type.ClrType, a =>
{
//表名
var relationalTableName = type.FindAnnotation("Relational:TableName");
if (relationalTableName != null)
a.Name(relationalTableName.Value?.ToString() ?? type.ClrType.Name);
//表名
var relationalTableName = type.FindAnnotation("Relational:TableName");
if (relationalTableName != null)
a.Name(relationalTableName.Value?.ToString() ?? type.ClrType.Name);
foreach (var prop in type.GetProperties()) {
foreach (var prop in type.GetProperties())
{
var freeProp = a.Property(prop.Name);
var freeProp = a.Property(prop.Name);
//列名
var relationalColumnName = prop.FindAnnotation("Relational:ColumnName");
if (relationalColumnName != null)
freeProp.Name(relationalColumnName.Value?.ToString() ?? prop.Name);
//列名
var relationalColumnName = prop.FindAnnotation("Relational:ColumnName");
if (relationalColumnName != null)
freeProp.Name(relationalColumnName.Value?.ToString() ?? prop.Name);
//主键
freeProp.IsPrimary(prop.IsPrimaryKey());
//主键
freeProp.IsPrimary(prop.IsPrimaryKey());
//自增
freeProp.IsIdentity(
prop.ValueGenerated == ValueGenerated.Never ||
prop.ValueGenerated == ValueGenerated.OnAdd ||
prop.GetAnnotations().Where(z =>
z.Name == "SqlServer:ValueGenerationStrategy" && z.Value.ToString().Contains("IdentityColumn") //sqlserver 自增
|| z.Value.ToString().Contains("IdentityColumn") //其他数据库实现未经测试
).Any()
);
//自增
freeProp.IsIdentity(
prop.ValueGenerated == ValueGenerated.Never ||
prop.ValueGenerated == ValueGenerated.OnAdd ||
prop.GetAnnotations().Where(z =>
z.Name == "SqlServer:ValueGenerationStrategy" && z.Value.ToString().Contains("IdentityColumn") //sqlserver 自增
|| z.Value.ToString().Contains("IdentityColumn") //其他数据库实现未经测试
).Any()
);
//可空
freeProp.IsNullable(prop.AfterSaveBehavior != PropertySaveBehavior.Throw);
//可空
freeProp.IsNullable(prop.AfterSaveBehavior != PropertySaveBehavior.Throw);
//类型
var relationalColumnType = prop.FindAnnotation("Relational:ColumnType");
if (relationalColumnType != null) {
//类型
var relationalColumnType = prop.FindAnnotation("Relational:ColumnType");
if (relationalColumnType != null)
{
var dbType = relationalColumnType.ToString();
if (!string.IsNullOrEmpty(dbType)) {
var dbType = relationalColumnType.ToString();
if (!string.IsNullOrEmpty(dbType))
{
var maxLength = prop.FindAnnotation("MaxLength");
if (maxLength != null)
dbType += $"({maxLength})";
var maxLength = prop.FindAnnotation("MaxLength");
if (maxLength != null)
dbType += $"({maxLength})";
freeProp.DbType(dbType);
}
}
}
});
}
}
freeProp.DbType(dbType);
}
}
}
});
}
}
}

View File

@ -1,30 +1,30 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:58143",
"sslPort": 44349
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:58143",
"sslPort": 44349
}
},
"efcore_to_freesql": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/values",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"efcore_to_freesql": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/values",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
}

View File

@ -22,57 +22,59 @@ namespace efcore_to_freesql
{
Configuration = configuration;
Fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.Build();
Fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.Build();
DBContexts.BaseDBContext.Fsql = Fsql;
DBContexts.BaseDBContext.Fsql = Fsql;
var sql11 = Fsql.Select<Topic1>().ToSql();
//SELECT a."Id", a."Title", a."CreateTime" FROM "Topic1" a
var sql12 = Fsql.Insert<Topic1>().AppendData(new Topic1()).ToSql();
//INSERT INTO "Topic1"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0)
var sql11 = Fsql.Select<Topic1>().ToSql();
//SELECT a."Id", a."Title", a."CreateTime" FROM "Topic1" a
var sql12 = Fsql.Insert<Topic1>().AppendData(new Topic1()).ToSql();
//INSERT INTO "Topic1"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0)
var sql21 = Fsql.Select<Topic2>().ToSql();
//SELECT a."Id", a."Title", a."CreateTime" FROM "Topic2" a
var sql22 = Fsql.Insert<Topic2>().AppendData(new Topic2()).ToSql();
//INSERT INTO "Topic2"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0)
var sql21 = Fsql.Select<Topic2>().ToSql();
//SELECT a."Id", a."Title", a."CreateTime" FROM "Topic2" a
var sql22 = Fsql.Insert<Topic2>().AppendData(new Topic2()).ToSql();
//INSERT INTO "Topic2"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0)
using (var db = new Topic1Context()) {
db.Topic1s.Add(new Topic1());
}
using (var db = new Topic2Context()) {
db.Topic2s.Add(new Topic2());
}
using (var db = new Topic1Context())
{
db.Topic1s.Add(new Topic1());
}
using (var db = new Topic2Context())
{
db.Topic2s.Add(new Topic2());
}
var sql13 = Fsql.Select<Topic1>().ToSql();
//SELECT a."topic1_id", a."Title", a."CreateTime" FROM "topic1_sss" a
var sql14 = Fsql.Insert<Topic1>().AppendData(new Topic1()).ToSql();
//INSERT INTO "topic1_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0)
var sql13 = Fsql.Select<Topic1>().ToSql();
//SELECT a."topic1_id", a."Title", a."CreateTime" FROM "topic1_sss" a
var sql14 = Fsql.Insert<Topic1>().AppendData(new Topic1()).ToSql();
//INSERT INTO "topic1_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0)
var sql23 = Fsql.Select<Topic2>().ToSql();
//SELECT a."topic2_id", a."Title", a."CreateTime" FROM "topic2_sss" a
var sql24 = Fsql.Insert<Topic2>().AppendData(new Topic2()).ToSql();
//INSERT INTO "topic2_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0)
}
var sql23 = Fsql.Select<Topic2>().ToSql();
//SELECT a."topic2_id", a."Title", a."CreateTime" FROM "topic2_sss" a
var sql24 = Fsql.Insert<Topic2>().AppendData(new Topic2()).ToSql();
//INSERT INTO "topic2_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0)
}
public IConfiguration Configuration { get; }
public IFreeSql Fsql { get; }
public IConfiguration Configuration { get; }
public IFreeSql Fsql { get; }
public void ConfigureServices(IServiceCollection services)
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IFreeSql>(Fsql);
services.AddMvc();
services.AddSingleton<IFreeSql>(Fsql);
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseDeveloperExceptionPage();
app.UseMvc();
}
app.UseDeveloperExceptionPage();
app.UseMvc();
}
}
}

View File

@ -1,9 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
}

View File

@ -1,8 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@ -14,288 +14,317 @@ namespace orm_vs
{
class Program
{
static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=20")
.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=20")
.UseAutoSyncStructure(false)
.UseNoneCommandParameter(true)
//.UseConfigEntityFromDbFirst(true)
.Build();
static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=20")
.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=20")
.UseAutoSyncStructure(false)
.UseNoneCommandParameter(true)
//.UseConfigEntityFromDbFirst(true)
.Build();
static SqlSugarClient sugar {
get => new SqlSugarClient(new ConnectionConfig() {
//不欺负让连接池100个最小
//ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20",
//DbType = DbType.SqlServer,
ConnectionString = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=20;Max Pool Size=20",
DbType = DbType.MySql,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
}
static SqlSugarClient sugar
{
get => new SqlSugarClient(new ConnectionConfig()
{
//不欺负让连接池100个最小
//ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20",
//DbType = DbType.SqlServer,
ConnectionString = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=20;Max Pool Size=20",
DbType = DbType.MySql,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
}
class SongContext : DbContext {
public DbSet<Song> Songs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
//optionsBuilder.UseSqlServer(@"Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=21;Max Pool Size=21");
optionsBuilder.UseMySql("Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=21;Max Pool Size=21");
}
}
class SongContext : DbContext
{
public DbSet<Song> Songs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//optionsBuilder.UseSqlServer(@"Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=21;Max Pool Size=21");
optionsBuilder.UseMySql("Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=21;Max Pool Size=21");
}
}
static void Main(string[] args) {
static void Main(string[] args)
{
fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag));
//sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag));
//sugar创建表失败SqlSugar.SqlSugarException: Sequence contains no elements
fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag));
//sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag));
//sugar创建表失败SqlSugar.SqlSugarException: Sequence contains no elements
sugar.Aop.OnLogExecuted = (s, e) => {
Trace.WriteLine(s);
};
//测试前清空数据
fsql.Delete<Song>().Where(a => a.Id > 0).ExecuteAffrows();
sugar.Deleteable<Song>().Where(a => a.Id > 0).ExecuteCommand();
fsql.Ado.ExecuteNonQuery("delete from efcore_song");
sugar.Aop.OnLogExecuted = (s, e) =>
{
Trace.WriteLine(s);
};
//测试前清空数据
fsql.Delete<Song>().Where(a => a.Id > 0).ExecuteAffrows();
sugar.Deleteable<Song>().Where(a => a.Id > 0).ExecuteCommand();
fsql.Ado.ExecuteNonQuery("delete from efcore_song");
var sb = new StringBuilder();
Console.WriteLine("插入性能:");
Insert(sb, 1000, 1);
Console.Write(sb.ToString());
sb.Clear();
Insert(sb, 1000, 10);
Console.Write(sb.ToString());
sb.Clear();
var sb = new StringBuilder();
Console.WriteLine("插入性能:");
Insert(sb, 1000, 1);
Console.Write(sb.ToString());
sb.Clear();
Insert(sb, 1000, 10);
Console.Write(sb.ToString());
sb.Clear();
Insert(sb, 1, 1000);
Console.Write(sb.ToString());
sb.Clear();
Insert(sb, 1, 10000);
Console.Write(sb.ToString());
sb.Clear();
Insert(sb, 1, 50000);
Console.Write(sb.ToString());
sb.Clear();
Insert(sb, 1, 100000);
Console.Write(sb.ToString());
sb.Clear();
Insert(sb, 1, 1000);
Console.Write(sb.ToString());
sb.Clear();
Insert(sb, 1, 10000);
Console.Write(sb.ToString());
sb.Clear();
Insert(sb, 1, 50000);
Console.Write(sb.ToString());
sb.Clear();
Insert(sb, 1, 100000);
Console.Write(sb.ToString());
sb.Clear();
Console.WriteLine("查询性能:");
Select(sb, 1000, 1);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1000, 10);
Console.Write(sb.ToString());
sb.Clear();
Console.WriteLine("查询性能:");
Select(sb, 1000, 1);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1000, 10);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1, 1000);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1, 10000);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1, 50000);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1, 100000);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1, 1000);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1, 10000);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1, 50000);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1, 100000);
Console.Write(sb.ToString());
sb.Clear();
Console.WriteLine("更新:");
Update(sb, 1000, 1);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1000, 10);
Console.Write(sb.ToString());
sb.Clear();
Console.WriteLine("更新:");
Update(sb, 1000, 1);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1000, 10);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1, 1000);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1, 10000);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1, 50000);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1, 100000);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1, 1000);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1, 10000);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1, 50000);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1, 100000);
Console.Write(sb.ToString());
sb.Clear();
Console.WriteLine("测试结束,按任意键退出...");
Console.ReadKey();
}
Console.WriteLine("测试结束,按任意键退出...");
Console.ReadKey();
}
static void Select(StringBuilder sb, int forTime, int size) {
Stopwatch sw = new Stopwatch();
sw.Restart();
for (var a = 0; a < forTime; a++)
fsql.Select<Song>().Limit(size).ToList();
sw.Stop();
sb.AppendLine($"FreeSql Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
static void Select(StringBuilder sb, int forTime, int size)
{
Stopwatch sw = new Stopwatch();
sw.Restart();
for (var a = 0; a < forTime; a++)
fsql.Select<Song>().Limit(size).ToList();
sw.Stop();
sb.AppendLine($"FreeSql Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
sw.Restart();
for (var a = 0; a < forTime; a++)
sugar.Queryable<Song>().Take(size).ToList();
sw.Stop();
sb.AppendLine($"SqlSugar Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
sw.Restart();
for (var a = 0; a < forTime; a++)
sugar.Queryable<Song>().Take(size).ToList();
sw.Stop();
sb.AppendLine($"SqlSugar Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
sw.Restart();
for (var a = 0; a < forTime; a++) {
using (var db = new SongContext()) {
db.Songs.Take(size).AsNoTracking().ToList();
}
}
sw.Stop();
sb.AppendLine($"EFCore Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
}
sw.Restart();
for (var a = 0; a < forTime; a++)
{
using (var db = new SongContext())
{
db.Songs.Take(size).AsNoTracking().ToList();
}
}
sw.Stop();
sb.AppendLine($"EFCore Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
}
static void Insert(StringBuilder sb, int forTime, int size) {
var songs = Enumerable.Range(0, size).Select(a => new Song {
Create_time = DateTime.Now,
Is_deleted = false,
Title = $"Insert_{a}",
Url = $"Url_{a}"
});
static void Insert(StringBuilder sb, int forTime, int size)
{
var songs = Enumerable.Range(0, size).Select(a => new Song
{
Create_time = DateTime.Now,
Is_deleted = false,
Title = $"Insert_{a}",
Url = $"Url_{a}"
});
//预热
fsql.Insert(songs.First()).ExecuteAffrows();
sugar.Insertable(songs.First()).ExecuteCommand();
using (var db = new SongContext()) {
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.AddRange(songs.First());
db.SaveChanges();
}
Stopwatch sw = new Stopwatch();
//预热
fsql.Insert(songs.First()).ExecuteAffrows();
sugar.Insertable(songs.First()).ExecuteCommand();
using (var db = new SongContext())
{
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.AddRange(songs.First());
db.SaveChanges();
}
Stopwatch sw = new Stopwatch();
sw.Restart();
for (var a = 0; a < forTime; a++) {
fsql.Insert(songs).ExecuteAffrows();
//using (var db = new FreeSongContext()) {
// //db.Configuration.AutoDetectChangesEnabled = false;
// db.Songs.AddRange(songs.ToArray());
// db.SaveChanges();
//}
}
sw.Stop();
sb.AppendLine($"FreeSql Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
sw.Restart();
for (var a = 0; a < forTime; a++)
{
fsql.Insert(songs).ExecuteAffrows();
//using (var db = new FreeSongContext()) {
// //db.Configuration.AutoDetectChangesEnabled = false;
// db.Songs.AddRange(songs.ToArray());
// db.SaveChanges();
//}
}
sw.Stop();
sb.AppendLine($"FreeSql Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
sw.Restart();
Exception sugarEx = null;
try {
for (var a = 0; a < forTime; a++)
sugar.Insertable(songs.ToArray()).ExecuteCommand();
} catch (Exception ex) {
sugarEx = ex;
}
sw.Stop();
sb.AppendLine($"SqlSugar Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));
sw.Restart();
Exception sugarEx = null;
try
{
for (var a = 0; a < forTime; a++)
sugar.Insertable(songs.ToArray()).ExecuteCommand();
}
catch (Exception ex)
{
sugarEx = ex;
}
sw.Stop();
sb.AppendLine($"SqlSugar Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));
sw.Restart();
for (var a = 0; a < forTime; a++) {
sw.Restart();
for (var a = 0; a < forTime; a++)
{
using (var db = new SongContext()) {
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.AddRange(songs.ToArray());
db.SaveChanges();
}
}
sw.Stop();
sb.AppendLine($"EFCore Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
}
using (var db = new SongContext())
{
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.AddRange(songs.ToArray());
db.SaveChanges();
}
}
sw.Stop();
sb.AppendLine($"EFCore Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
}
static void Update(StringBuilder sb, int forTime, int size) {
Stopwatch sw = new Stopwatch();
static void Update(StringBuilder sb, int forTime, int size)
{
Stopwatch sw = new Stopwatch();
var songs = fsql.Select<Song>().Limit(size).ToList();
sw.Restart();
for (var a = 0; a < forTime; a++) {
fsql.Update<Song>().SetSource(songs).ExecuteAffrows();
}
sw.Stop();
sb.AppendLine($"FreeSql Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
var songs = fsql.Select<Song>().Limit(size).ToList();
sw.Restart();
for (var a = 0; a < forTime; a++)
{
fsql.Update<Song>().SetSource(songs).ExecuteAffrows();
}
sw.Stop();
sb.AppendLine($"FreeSql Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
songs = sugar.Queryable<Song>().Take(size).ToList();
sw.Restart();
Exception sugarEx = null;
try {
for (var a = 0; a < forTime; a++)
sugar.Updateable(songs).ExecuteCommand();
} catch (Exception ex) {
sugarEx = ex;
}
sw.Stop();
sb.AppendLine($"SqlSugar Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));
songs = sugar.Queryable<Song>().Take(size).ToList();
sw.Restart();
Exception sugarEx = null;
try
{
for (var a = 0; a < forTime; a++)
sugar.Updateable(songs).ExecuteCommand();
}
catch (Exception ex)
{
sugarEx = ex;
}
sw.Stop();
sb.AppendLine($"SqlSugar Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));
using (var db = new SongContext()) {
songs = db.Songs.Take(size).AsNoTracking().ToList();
}
sw.Restart();
for (var a = 0; a < forTime; a++) {
using (var db = new SongContext())
{
songs = db.Songs.Take(size).AsNoTracking().ToList();
}
sw.Restart();
for (var a = 0; a < forTime; a++)
{
using (var db = new SongContext()) {
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.UpdateRange(songs.ToArray());
db.SaveChanges();
}
}
sw.Stop();
sb.AppendLine($"EFCore Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
}
}
using (var db = new SongContext())
{
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.UpdateRange(songs.ToArray());
db.SaveChanges();
}
}
sw.Stop();
sb.AppendLine($"EFCore Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
}
}
[FreeSql.DataAnnotations.Table(Name = "freesql_song")]
[SugarTable("sugar_song")]
[Table("efcore_song")]
public class Song {
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime? Create_time { get; set; }
public bool? Is_deleted { get; set; }
public string Title { get; set; }
public string Url { get; set; }
[FreeSql.DataAnnotations.Table(Name = "freesql_song")]
[SugarTable("sugar_song")]
[Table("efcore_song")]
public class Song
{
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime? Create_time { get; set; }
public bool? Is_deleted { get; set; }
public string Title { get; set; }
public string Url { get; set; }
[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual ICollection<Tag> Tags { get; set; }
}
[FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")]
[SugarTable("sugar_song_tag")]
[Table("efcore_song_tag")]
public class Song_tag {
public int Song_id { get; set; }
[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual Song Song { get; set; }
[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual ICollection<Tag> Tags { get; set; }
}
[FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")]
[SugarTable("sugar_song_tag")]
[Table("efcore_song_tag")]
public class Song_tag
{
public int Song_id { get; set; }
[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual Song Song { get; set; }
public int Tag_id { get; set; }
[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual Tag Tag { get; set; }
}
[FreeSql.DataAnnotations.Table(Name = "freesql_tag")]
[SugarTable("sugar_tag")]
[Table("efcore_tag")]
public class Tag {
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? Parent_id { get; set; }
[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual Tag Parent { get; set; }
public int Tag_id { get; set; }
[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual Tag Tag { get; set; }
}
[FreeSql.DataAnnotations.Table(Name = "freesql_tag")]
[SugarTable("sugar_tag")]
[Table("efcore_tag")]
public class Tag
{
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? Parent_id { get; set; }
[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual Tag Parent { get; set; }
public decimal? Ddd { get; set; }
public string Name { get; set; }
public decimal? Ddd { get; set; }
public string Name { get; set; }
[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual ICollection<Song> Songs { get; set; }
[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual ICollection<Tag> Tags { get; set; }
}
[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual ICollection<Song> Songs { get; set; }
[SugarColumn(IsIgnore = true)]
[NotMapped]
public virtual ICollection<Tag> Tags { get; set; }
}
}

View File

@ -6,93 +6,107 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace restful.Controllers {
namespace restful.Controllers
{
public class SongRepository : GuidRepository<Song> {
public SongRepository(IFreeSql fsql) : base(fsql) {
}
}
public class SongRepository : GuidRepository<Song>
{
public SongRepository(IFreeSql fsql) : base(fsql)
{
}
}
[Route("restapi/[controller]")]
public class SongsController : Controller {
[Route("restapi/[controller]")]
public class SongsController : Controller
{
BaseRepository<Song, int> _songRepository;
BaseRepository<Song, int> _songRepository;
public class xxxx {
public int Id { get; set; }
public class xxxx
{
public int Id { get; set; }
public bool IsDeleted { get; set; }
}
public bool IsDeleted { get; set; }
}
public SongsController(IFreeSql fsql,
GuidRepository<Song> repos1,
GuidRepository<xxxx> repos2,
DefaultRepository<Song, int> repos11,
DefaultRepository<xxxx, int> repos21,
public SongsController(IFreeSql fsql,
GuidRepository<Song> repos1,
GuidRepository<xxxx> repos2,
BaseRepository<Song> repos3, BaseRepository<Song, int> repos4,
IBasicRepository<Song> repos31, IBasicRepository<Song, int> repos41,
IReadOnlyRepository<Song> repos311, IReadOnlyRepository<Song, int> repos411,
DefaultRepository<Song, int> repos11,
DefaultRepository<xxxx, int> repos21,
SongRepository reposSong
) {
_songRepository = repos4;
BaseRepository<Song> repos3, BaseRepository<Song, int> repos4,
IBasicRepository<Song> repos31, IBasicRepository<Song, int> repos41,
IReadOnlyRepository<Song> repos311, IReadOnlyRepository<Song, int> repos411,
//test code
var curd1 = fsql.GetRepository<Song, int>();
var curd2 = fsql.GetRepository<Song, string>();
var curd3 = fsql.GetRepository<Song, Guid>();
var curd4 = fsql.GetGuidRepository<Song>();
SongRepository reposSong
)
{
_songRepository = repos4;
Console.WriteLine(repos1.Select.ToSql());
Console.WriteLine(reposSong.Select.ToSql());
//test code
var curd1 = fsql.GetRepository<Song, int>();
var curd2 = fsql.GetRepository<Song, string>();
var curd3 = fsql.GetRepository<Song, Guid>();
var curd4 = fsql.GetGuidRepository<Song>();
Console.WriteLine(repos2.Select.ToSql());
Console.WriteLine(repos21.Select.ToSql());
Console.WriteLine(repos1.Select.ToSql());
Console.WriteLine(reposSong.Select.ToSql());
using (reposSong.DataFilter.DisableAll()) {
Console.WriteLine(reposSong.Select.ToSql());
}
}
Console.WriteLine(repos2.Select.ToSql());
Console.WriteLine(repos21.Select.ToSql());
[HttpGet]
public Task<List<Song>> GetItems([FromQuery] string key, [FromQuery] int page = 1, [FromQuery] int limit = 20) {
return _songRepository.Select.WhereIf(!string.IsNullOrEmpty(key), a => a.Title.Contains(key)).Page(page, limit).ToListAsync();
}
using (reposSong.DataFilter.DisableAll())
{
Console.WriteLine(reposSong.Select.ToSql());
}
}
[HttpGet("{id}")]
public Task<Song> GetItem([FromRoute] int id) {
return _songRepository.FindAsync(id);
}
[HttpGet]
public Task<List<Song>> GetItems([FromQuery] string key, [FromQuery] int page = 1, [FromQuery] int limit = 20)
{
return _songRepository.Select.WhereIf(!string.IsNullOrEmpty(key), a => a.Title.Contains(key)).Page(page, limit).ToListAsync();
}
public class ModelSong {
public string title { get; set; }
}
[HttpGet("{id}")]
public Task<Song> GetItem([FromRoute] int id)
{
return _songRepository.FindAsync(id);
}
[HttpPost, ProducesResponseType(201)]
public Task<Song> Create([FromBody] ModelSong model) {
return _songRepository.InsertAsync(new Song { Title = model.title });
}
public class ModelSong
{
public string title { get; set; }
}
[HttpPut("{id}")]
public Task Update([FromRoute] int id, [FromBody] ModelSong model) {
return _songRepository.UpdateAsync(new Song { Id = id, Title = model.title });
}
[HttpPost, ProducesResponseType(201)]
public Task<Song> Create([FromBody] ModelSong model)
{
return _songRepository.InsertAsync(new Song { Title = model.title });
}
[HttpPatch("{id}")]
async public Task<Song> UpdateDiy([FromRoute] int id, [FromForm] string title) {
var up = _songRepository.UpdateDiy.Where(a => a.Id == id);
if (!string.IsNullOrEmpty(title)) up.Set(a => a.Title, title);
var ret = await up.ExecuteUpdatedAsync();
return ret.FirstOrDefault();
}
[HttpPut("{id}")]
public Task Update([FromRoute] int id, [FromBody] ModelSong model)
{
return _songRepository.UpdateAsync(new Song { Id = id, Title = model.title });
}
[HttpDelete("{id}"), ProducesResponseType(204)]
public Task Delete([FromRoute] int id) {
return _songRepository.DeleteAsync(a => a.Id == id);
}
}
[HttpPatch("{id}")]
async public Task<Song> UpdateDiy([FromRoute] int id, [FromForm] string title)
{
var up = _songRepository.UpdateDiy.Where(a => a.Id == id);
if (!string.IsNullOrEmpty(title)) up.Set(a => a.Title, title);
var ret = await up.ExecuteUpdatedAsync();
return ret.FirstOrDefault();
}
[HttpDelete("{id}"), ProducesResponseType(204)]
public Task Delete([FromRoute] int id)
{
return _songRepository.DeleteAsync(a => a.Id == id);
}
}
}

View File

@ -1,11 +1,13 @@
using FreeSql.DataAnnotations;
using repository_01;
namespace restful.Entitys {
public class Song {
namespace restful.Entitys
{
public class Song
{
[Column(IsIdentity = true)]
public int Id { get; set; }
public string Title { get; set; }
}
[Column(IsIdentity = true)]
public int Id { get; set; }
public string Title { get; set; }
}
}

View File

@ -1,27 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:52751/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:52751/",
"sslPort": 0
}
},
"repository_01": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:52752/"
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"repository_01": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:52752/"
}
}
}
}

View File

@ -13,86 +13,98 @@ using System.Diagnostics;
using System.Linq;
using System.Text;
namespace repository_01 {
namespace repository_01
{
/// <summary>
/// 用户密码信息
/// </summary>
public class Sys1UserLogOn {
[Column(IsPrimary = true, Name = "Id")]
public Guid UserLogOnId { get; set; }
public virtual Sys1User User { get; set; }
}
public class Sys1User {
[Column(IsPrimary = true, Name = "Id")]
public Guid UserId { get; set; }
public virtual Sys1UserLogOn UserLogOn { get; set; }
}
public class Startup {
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) {
Configuration = configuration;
/// <summary>
/// 用户密码信息
/// </summary>
public class Sys1UserLogOn
{
[Column(IsPrimary = true, Name = "Id")]
public Guid UserLogOnId { get; set; }
public virtual Sys1User User { get; set; }
}
public class Sys1User
{
[Column(IsPrimary = true, Name = "Id")]
public Guid UserId { get; set; }
public virtual Sys1UserLogOn UserLogOn { get; set; }
}
Fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
public class Startup
{
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
{
Configuration = configuration;
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
.Build();
Fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
var sysu = new Sys1User { };
Fsql.Insert<Sys1User>().AppendData(sysu).ExecuteAffrows();
Fsql.Insert<Sys1UserLogOn>().AppendData(new Sys1UserLogOn { UserLogOnId = sysu.UserId }).ExecuteAffrows();
var a = Fsql.Select<Sys1UserLogOn>().ToList();
var b = Fsql.Select<Sys1UserLogOn>().Any();
}
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
.Build();
public IConfiguration Configuration { get; }
public static IFreeSql Fsql { get; private set; }
var sysu = new Sys1User { };
Fsql.Insert<Sys1User>().AppendData(sysu).ExecuteAffrows();
Fsql.Insert<Sys1UserLogOn>().AppendData(new Sys1UserLogOn { UserLogOnId = sysu.UserId }).ExecuteAffrows();
var a = Fsql.Select<Sys1UserLogOn>().ToList();
var b = Fsql.Select<Sys1UserLogOn>().Any();
}
public void ConfigureServices(IServiceCollection services) {
public IConfiguration Configuration { get; }
public static IFreeSql Fsql { get; private set; }
//services.AddTransient(s => s.)
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwaggerGen(options => {
options.SwaggerDoc("v1", new Info {
Version = "v1",
Title = "FreeSql.RESTful API"
});
//options.IncludeXmlComments(xmlPath);
});
//services.AddTransient(s => s.)
services.AddSingleton<IFreeSql>(Fsql);
services.AddMvc();
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "FreeSql.RESTful API"
});
//options.IncludeXmlComments(xmlPath);
});
services.AddFreeRepository(filter => {
filter
//.Apply<Song>("test", a => a.Title == DateTime.Now.ToString() + System.Threading.Thread.CurrentThread.ManagedThreadId)
.Apply<ISoftDelete>("softdelete", a => a.IsDeleted == false);
}, this.GetType().Assembly);
}
services.AddSingleton<IFreeSql>(Fsql);
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
Console.InputEncoding = Encoding.GetEncoding("GB2312");
services.AddFreeRepository(filter =>
{
filter
//.Apply<Song>("test", a => a.Title == DateTime.Now.ToString() + System.Threading.Thread.CurrentThread.ManagedThreadId)
.Apply<ISoftDelete>("softdelete", a => a.IsDeleted == false);
}, this.GetType().Assembly);
}
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
Console.InputEncoding = Encoding.GetEncoding("GB2312");
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
app.UseDeveloperExceptionPage();
app.UseMvc();
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
});
}
}
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
app.UseDeveloperExceptionPage();
app.UseMvc();
public interface ISoftDelete {
bool IsDeleted { get; set; }
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
});
}
}
public interface ISoftDelete
{
bool IsDeleted { get; set; }
}
}

View File

@ -1,9 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Warning",
"Microsoft": "Warning"
}
}
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Warning",
"Microsoft": "Warning"
}
}
}

View File

@ -1,8 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@ -4,56 +4,66 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace restful.Controllers {
namespace restful.Controllers
{
[Route("restapi/[controller]")]
public class SongsController : Controller {
[Route("restapi/[controller]")]
public class SongsController : Controller
{
IFreeSql _fsql;
IFreeSql _fsql;
public SongsController(IFreeSql fsql) {
_fsql = fsql;
}
public SongsController(IFreeSql fsql)
{
_fsql = fsql;
}
[HttpGet]
public Task<List<Song>> GetItems([FromQuery] string key, [FromQuery] int page = 1, [FromQuery] int limit = 20) {
return _fsql.Select<Song>().WhereIf(!string.IsNullOrEmpty(key), a => a.Title.Contains(key)).Page(page, limit).ToListAsync();
}
[HttpGet]
public Task<List<Song>> GetItems([FromQuery] string key, [FromQuery] int page = 1, [FromQuery] int limit = 20)
{
return _fsql.Select<Song>().WhereIf(!string.IsNullOrEmpty(key), a => a.Title.Contains(key)).Page(page, limit).ToListAsync();
}
[HttpGet("{id}")]
public Task<Song> GetItem([FromRoute] int id) {
return _fsql.Select<Song>().Where(a => a.Id == id).ToOneAsync();
}
[HttpGet("{id}")]
public Task<Song> GetItem([FromRoute] int id)
{
return _fsql.Select<Song>().Where(a => a.Id == id).ToOneAsync();
}
public class ModelSong {
public string title { get; set; }
}
public class ModelSong
{
public string title { get; set; }
}
[HttpPost, ProducesResponseType(201)]
async public Task<Song> Create([FromBody] ModelSong model) {
var ret = await _fsql.Insert<Song>().AppendData(new Song { Title = model.title }).ExecuteInsertedAsync();
return ret.FirstOrDefault();
}
[HttpPost, ProducesResponseType(201)]
async public Task<Song> Create([FromBody] ModelSong model)
{
var ret = await _fsql.Insert<Song>().AppendData(new Song { Title = model.title }).ExecuteInsertedAsync();
return ret.FirstOrDefault();
}
[HttpPut("{id}")]
async public Task<Song> Update([FromRoute] int id, [FromBody] ModelSong model) {
var ret = await _fsql.Update<Song>().SetSource(new Song { Id = id, Title = model.title }).ExecuteUpdatedAsync();
return ret.FirstOrDefault();
}
[HttpPut("{id}")]
async public Task<Song> Update([FromRoute] int id, [FromBody] ModelSong model)
{
var ret = await _fsql.Update<Song>().SetSource(new Song { Id = id, Title = model.title }).ExecuteUpdatedAsync();
return ret.FirstOrDefault();
}
[HttpPatch("{id}")]
async public Task<Song> UpdateDiy([FromRoute] int id, [FromForm] string title) {
var up = _fsql.Update<Song>().Where(a => a.Id == id);
if (!string.IsNullOrEmpty(title)) up.Set(a => a.Title, title);
var ret = await up.ExecuteUpdatedAsync();
return ret.FirstOrDefault();
}
[HttpPatch("{id}")]
async public Task<Song> UpdateDiy([FromRoute] int id, [FromForm] string title)
{
var up = _fsql.Update<Song>().Where(a => a.Id == id);
if (!string.IsNullOrEmpty(title)) up.Set(a => a.Title, title);
var ret = await up.ExecuteUpdatedAsync();
return ret.FirstOrDefault();
}
[HttpDelete("{id}"), ProducesResponseType(204)]
async public Task<Song> Delete([FromRoute] int id) {
var ret = await _fsql.Delete<Song>().Where(a => a.Id == id).ExecuteDeletedAsync();
return ret.FirstOrDefault();
}
}
[HttpDelete("{id}"), ProducesResponseType(204)]
async public Task<Song> Delete([FromRoute] int id)
{
var ret = await _fsql.Delete<Song>().Where(a => a.Id == id).ExecuteDeletedAsync();
return ret.FirstOrDefault();
}
}
}

View File

@ -1,10 +1,12 @@
using FreeSql.DataAnnotations;
namespace restful.Entitys {
public class Song {
namespace restful.Entitys
{
public class Song
{
[Column(IsIdentity = true)]
public int Id { get; set; }
public string Title { get; set; }
}
[Column(IsIdentity = true)]
public int Id { get; set; }
public string Title { get; set; }
}
}

View File

@ -1,27 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:49778/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:49778/",
"sslPort": 0
}
},
"FreeSql.RESTful.Demo": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:49779/"
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"FreeSql.RESTful.Demo": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:49779/"
}
}
}
}

View File

@ -7,61 +7,71 @@ using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Text;
namespace restful {
public class Startup {
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) {
Configuration = configuration;
namespace restful
{
public class Startup
{
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
{
Configuration = configuration;
Fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.Build();
Fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.Build();
Fsql.Aop.CurdAfter = (s, e) => {
if (e.ElapsedMilliseconds > 200) {
//记录日志
//发送短信给负责人
}
};
Fsql.Aop.CurdAfter = (s, e) =>
{
if (e.ElapsedMilliseconds > 200)
{
//记录日志
//发送短信给负责人
}
};
//Fsql.Aop.Where = (s, e) => {
// if (e.Parameters[0]?.ToString() == "1")
// e.IsCancel = true;
//};
}
//Fsql.Aop.Where = (s, e) => {
// if (e.Parameters[0]?.ToString() == "1")
// e.IsCancel = true;
//};
}
public IConfiguration Configuration { get; }
public IFreeSql Fsql { get; }
public IConfiguration Configuration { get; }
public IFreeSql Fsql { get; }
public void ConfigureServices(IServiceCollection services) {
services.AddSingleton<IFreeSql>(Fsql);
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IFreeSql>(Fsql);
services.AddMvc();
services.AddSwaggerGen(options => {
options.SwaggerDoc("v1", new Info {
Version = "v1",
Title = "FreeSql.RESTful API"
});
//options.IncludeXmlComments(xmlPath);
});
}
services.AddMvc();
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "FreeSql.RESTful API"
});
//options.IncludeXmlComments(xmlPath);
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
Console.InputEncoding = Encoding.GetEncoding("GB2312");
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
Console.InputEncoding = Encoding.GetEncoding("GB2312");
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
app.UseDeveloperExceptionPage();
app.UseMvc();
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
app.UseDeveloperExceptionPage();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
});
}
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
});
}
}
}

View File

@ -1,9 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
}

View File

@ -1,8 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@ -5,30 +5,34 @@ using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace FreeSql.Extensions.LazyLoading {
namespace FreeSql.Extensions.LazyLoading
{
public class LazyLoadingComplier {
public class LazyLoadingComplier
{
#if ns20
internal static Lazy<CSScriptLib.RoslynEvaluator> _compiler = new Lazy<CSScriptLib.RoslynEvaluator>(() => {
//var dlls = Directory.GetFiles(Directory.GetParent(Type.GetType("IFreeSql, FreeSql").Assembly.Location).FullName, "*.dll");
var compiler = new CSScriptLib.RoslynEvaluator();
compiler.DisableReferencingFromCode = false;
//compiler.DebugBuild = true;
//foreach (var dll in dlls) {
// Console.WriteLine(dll);
// var ass = Assembly.LoadFile(dll);
// compiler.ReferenceAssembly(ass);
//}
compiler
.ReferenceAssemblyOf<IFreeSql>()
.ReferenceDomainAssemblies();
return compiler;
});
internal static Lazy<CSScriptLib.RoslynEvaluator> _compiler = new Lazy<CSScriptLib.RoslynEvaluator>(() =>
{
//var dlls = Directory.GetFiles(Directory.GetParent(Type.GetType("IFreeSql, FreeSql").Assembly.Location).FullName, "*.dll");
var compiler = new CSScriptLib.RoslynEvaluator();
compiler.DisableReferencingFromCode = false;
//compiler.DebugBuild = true;
//foreach (var dll in dlls) {
// Console.WriteLine(dll);
// var ass = Assembly.LoadFile(dll);
// compiler.ReferenceAssembly(ass);
//}
compiler
.ReferenceAssemblyOf<IFreeSql>()
.ReferenceDomainAssemblies();
return compiler;
});
public static Assembly CompileCode(string cscode) {
return _compiler.Value.CompileCode(cscode);
}
public static Assembly CompileCode(string cscode)
{
return _compiler.Value.CompileCode(cscode);
}
#else
@ -52,5 +56,5 @@ namespace FreeSql.Extensions.LazyLoading {
}
#endif
}
}
}

View File

@ -5,150 +5,168 @@ using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace FreeSql {
public abstract partial class DbContext : IDisposable {
namespace FreeSql
{
public abstract partial class DbContext : IDisposable
{
internal IFreeSql _orm;
internal IFreeSql _fsql => _orm ?? throw new ArgumentNullException("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql");
internal IFreeSql _orm;
internal IFreeSql _fsql => _orm ?? throw new ArgumentNullException("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql");
public IFreeSql Orm => _fsql;
public IFreeSql Orm => _fsql;
protected IUnitOfWork _uowPriv;
internal IUnitOfWork _uow => _isUseUnitOfWork ? (_uowPriv ?? (_uowPriv = new UnitOfWork(_fsql))) : null;
internal bool _isUseUnitOfWork = true; //不使用工作单元事务
protected IUnitOfWork _uowPriv;
internal IUnitOfWork _uow => _isUseUnitOfWork ? (_uowPriv ?? (_uowPriv = new UnitOfWork(_fsql))) : null;
internal bool _isUseUnitOfWork = true; //不使用工作单元事务
public IUnitOfWork UnitOfWork => _uow;
public IUnitOfWork UnitOfWork => _uow;
DbContextOptions _options;
internal DbContextOptions Options {
get {
if (_options != null) return _options;
if (FreeSqlDbContextExtenssions._dicSetDbContextOptions.TryGetValue(Orm, out _options)) return _options;
_options = new DbContextOptions();
return _options;
}
}
DbContextOptions _options;
internal DbContextOptions Options
{
get
{
if (_options != null) return _options;
if (FreeSqlDbContextExtenssions._dicSetDbContextOptions.TryGetValue(Orm, out _options)) return _options;
_options = new DbContextOptions();
return _options;
}
}
static ConcurrentDictionary<Type, PropertyInfo[]> _dicGetDbSetProps = new ConcurrentDictionary<Type, PropertyInfo[]>();
protected DbContext() {
static ConcurrentDictionary<Type, PropertyInfo[]> _dicGetDbSetProps = new ConcurrentDictionary<Type, PropertyInfo[]>();
protected DbContext()
{
var builder = new DbContextOptionsBuilder();
OnConfiguring(builder);
_orm = builder._fsql;
var builder = new DbContextOptionsBuilder();
OnConfiguring(builder);
_orm = builder._fsql;
if (_orm != null) InitPropSets();
}
if (_orm != null) InitPropSets();
}
internal void InitPropSets() {
var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp =>
tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
.Where(a => a.PropertyType.IsGenericType &&
a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray());
internal void InitPropSets()
{
var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp =>
tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
.Where(a => a.PropertyType.IsGenericType &&
a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray());
foreach (var prop in props) {
var set = this.Set(prop.PropertyType.GenericTypeArguments[0]);
foreach (var prop in props)
{
var set = this.Set(prop.PropertyType.GenericTypeArguments[0]);
prop.SetValue(this, set);
AllSets.Add(prop.Name, set);
}
}
prop.SetValue(this, set);
AllSets.Add(prop.Name, set);
}
}
protected virtual void OnConfiguring(DbContextOptionsBuilder builder) {
}
protected virtual void OnConfiguring(DbContextOptionsBuilder builder)
{
protected Dictionary<Type, IDbSet> _dicSet = new Dictionary<Type, IDbSet>();
public DbSet<TEntity> Set<TEntity>() where TEntity : class => this.Set(typeof(TEntity)) as DbSet<TEntity>;
public virtual IDbSet Set(Type entityType) {
if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType];
var sd = Activator.CreateInstance(typeof(DbContextDbSet<>).MakeGenericType(entityType), this) as IDbSet;
if (entityType != typeof(object)) _dicSet.Add(entityType, sd);
return sd;
}
protected Dictionary<string, IDbSet> AllSets { get; } = new Dictionary<string, IDbSet>();
}
#region DbSet
/// <summary>
/// 添加
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void Add<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Add(data);
public void AddRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AddRange(data);
public Task AddAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddAsync(data);
public Task AddRangeAsync<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AddRangeAsync(data);
protected Dictionary<Type, IDbSet> _dicSet = new Dictionary<Type, IDbSet>();
public DbSet<TEntity> Set<TEntity>() where TEntity : class => this.Set(typeof(TEntity)) as DbSet<TEntity>;
public virtual IDbSet Set(Type entityType)
{
if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType];
var sd = Activator.CreateInstance(typeof(DbContextDbSet<>).MakeGenericType(entityType), this) as IDbSet;
if (entityType != typeof(object)) _dicSet.Add(entityType, sd);
return sd;
}
protected Dictionary<string, IDbSet> AllSets { get; } = new Dictionary<string, IDbSet>();
/// <summary>
/// 更新
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void Update<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Update(data);
public void UpdateRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().UpdateRange(data);
public Task UpdateAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().UpdateAsync(data);
public Task UpdateRangeAsync<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().UpdateRangeAsync(data);
#region DbSet
/// <summary>
/// 添加
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void Add<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Add(data);
public void AddRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AddRange(data);
public Task AddAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddAsync(data);
public Task AddRangeAsync<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AddRangeAsync(data);
/// <summary>
/// 删除
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void Remove<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Remove(data);
public void RemoveRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().RemoveRange(data);
/// <summary>
/// 更新
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void Update<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Update(data);
public void UpdateRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().UpdateRange(data);
public Task UpdateAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().UpdateAsync(data);
public Task UpdateRangeAsync<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().UpdateRangeAsync(data);
/// <summary>
/// 添加或更新
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void AddOrUpdate<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddOrUpdate(data);
public Task AddOrUpdateAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddOrUpdateAsync(data);
/// <summary>
/// 删除
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void Remove<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Remove(data);
public void RemoveRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().RemoveRange(data);
/// <summary>
/// 附加实体,可用于不查询就更新或删除
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void Attach<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Attach(data);
public void AttachRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AttachRange(data);
#endregion
/// <summary>
/// 添加或更新
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void AddOrUpdate<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddOrUpdate(data);
public Task AddOrUpdateAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddOrUpdateAsync(data);
internal class ExecCommandInfo {
public ExecCommandInfoType actionType { get; set; }
public IDbSet dbSet { get; set; }
public Type stateType { get; set; }
public object state { get; set; }
}
internal enum ExecCommandInfoType { Insert, Update, Delete }
Queue<ExecCommandInfo> _actions = new Queue<ExecCommandInfo>();
internal int _affrows = 0;
/// <summary>
/// 附加实体,可用于不查询就更新或删除
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void Attach<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Attach(data);
public void AttachRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AttachRange(data);
#endregion
internal void EnqueueAction(ExecCommandInfoType actionType, IDbSet dbSet, Type stateType, object state) {
_actions.Enqueue(new ExecCommandInfo { actionType = actionType, dbSet = dbSet, stateType = stateType, state = state });
}
internal class ExecCommandInfo
{
public ExecCommandInfoType actionType { get; set; }
public IDbSet dbSet { get; set; }
public Type stateType { get; set; }
public object state { get; set; }
}
internal enum ExecCommandInfoType { Insert, Update, Delete }
Queue<ExecCommandInfo> _actions = new Queue<ExecCommandInfo>();
internal int _affrows = 0;
~DbContext() {
this.Dispose();
}
bool _isdisposed = false;
public void Dispose() {
if (_isdisposed) return;
try {
_actions.Clear();
internal void EnqueueAction(ExecCommandInfoType actionType, IDbSet dbSet, Type stateType, object state)
{
_actions.Enqueue(new ExecCommandInfo { actionType = actionType, dbSet = dbSet, stateType = stateType, state = state });
}
foreach (var set in _dicSet)
try {
set.Value.Dispose();
} catch { }
~DbContext()
{
this.Dispose();
}
bool _isdisposed = false;
public void Dispose()
{
if (_isdisposed) return;
try
{
_actions.Clear();
_dicSet.Clear();
AllSets.Clear();
_uow?.Rollback();
} finally {
_isdisposed = true;
GC.SuppressFinalize(this);
}
}
}
foreach (var set in _dicSet)
try
{
set.Value.Dispose();
}
catch { }
_dicSet.Clear();
AllSets.Clear();
_uow?.Rollback();
}
finally
{
_isdisposed = true;
GC.SuppressFinalize(this);
}
}
}
}

View File

@ -5,115 +5,133 @@ using System.Reflection;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace FreeSql {
partial class DbContext {
namespace FreeSql
{
partial class DbContext
{
async public virtual Task<int> SaveChangesAsync() {
await ExecCommandAsync();
_uow?.Commit();
var ret = _affrows;
_affrows = 0;
return ret;
}
async public virtual Task<int> SaveChangesAsync()
{
await ExecCommandAsync();
_uow?.Commit();
var ret = _affrows;
_affrows = 0;
return ret;
}
static Dictionary<Type, Dictionary<string, Func<object, object[], Task<int>>>> _dicExecCommandDbContextBetchAsync = new Dictionary<Type, Dictionary<string, Func<object, object[], Task<int>>>>();
async internal Task ExecCommandAsync() {
if (isExecCommanding) return;
if (_actions.Any() == false) return;
isExecCommanding = true;
static Dictionary<Type, Dictionary<string, Func<object, object[], Task<int>>>> _dicExecCommandDbContextBetchAsync = new Dictionary<Type, Dictionary<string, Func<object, object[], Task<int>>>>();
async internal Task ExecCommandAsync()
{
if (isExecCommanding) return;
if (_actions.Any() == false) return;
isExecCommanding = true;
ExecCommandInfo oldinfo = null;
var states = new List<object>();
ExecCommandInfo oldinfo = null;
var states = new List<object>();
Func<string, Task<int>> dbContextBetch = methodName => {
if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
var arrType = oldinfo.stateType.MakeArrayType();
var dbsetType = oldinfo.dbSet.GetType().BaseType;
var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);
Func<string, Task<int>> dbContextBetch = methodName =>
{
if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
if (trydic.TryGetValue(methodName, out var tryfunc) == false)
{
var arrType = oldinfo.stateType.MakeArrayType();
var dbsetType = oldinfo.dbSet.GetType().BaseType;
var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);
var returnTarget = Expression.Label(typeof(Task<int>));
var parm1DbSet = Expression.Parameter(typeof(object));
var parm2Vals = Expression.Parameter(typeof(object[]));
var var1Vals = Expression.Variable(arrType);
tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
new[] { var1Vals },
Expression.Assign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
), new[] { parm1DbSet, parm2Vals }).Compile();
trydic.Add(methodName, tryfunc);
}
return tryfunc(oldinfo.dbSet, states.ToArray());
};
Func<Task> funcDelete = async () => {
_affrows += await dbContextBetch("DbContextBetchRemoveAsync");
states.Clear();
};
Func<Task> funcInsert = async () => {
_affrows += await dbContextBetch("DbContextBetchAddAsync");
states.Clear();
};
Func<bool, Task> funcUpdate = async (isLiveUpdate) => {
var affrows = 0;
if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
if (affrows == -999) { //最后一个元素已被删除
states.RemoveAt(states.Count - 1);
return;
}
if (affrows == -998 || affrows == -997) { //没有执行更新
var laststate = states[states.Count - 1];
states.Clear();
if (affrows == -997) states.Add(laststate); //保留最后一个
}
if (affrows > 0) {
_affrows += affrows;
var islastNotUpdated = states.Count != affrows;
var laststate = states[states.Count - 1];
states.Clear();
if (islastNotUpdated) states.Add(laststate); //保留最后一个
}
};
var returnTarget = Expression.Label(typeof(Task<int>));
var parm1DbSet = Expression.Parameter(typeof(object));
var parm2Vals = Expression.Parameter(typeof(object[]));
var var1Vals = Expression.Variable(arrType);
tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
new[] { var1Vals },
Expression.Assign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
), new[] { parm1DbSet, parm2Vals }).Compile();
trydic.Add(methodName, tryfunc);
}
return tryfunc(oldinfo.dbSet, states.ToArray());
};
Func<Task> funcDelete = async () =>
{
_affrows += await dbContextBetch("DbContextBetchRemoveAsync");
states.Clear();
};
Func<Task> funcInsert = async () =>
{
_affrows += await dbContextBetch("DbContextBetchAddAsync");
states.Clear();
};
Func<bool, Task> funcUpdate = async (isLiveUpdate) =>
{
var affrows = 0;
if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
if (affrows == -999)
{ //最后一个元素已被删除
states.RemoveAt(states.Count - 1);
return;
}
if (affrows == -998 || affrows == -997)
{ //没有执行更新
var laststate = states[states.Count - 1];
states.Clear();
if (affrows == -997) states.Add(laststate); //保留最后一个
}
if (affrows > 0)
{
_affrows += affrows;
var islastNotUpdated = states.Count != affrows;
var laststate = states[states.Count - 1];
states.Clear();
if (islastNotUpdated) states.Add(laststate); //保留最后一个
}
};
while (_actions.Any() || states.Any()) {
var info = _actions.Any() ? _actions.Dequeue() : null;
if (oldinfo == null) oldinfo = info;
var isLiveUpdate = false;
while (_actions.Any() || states.Any())
{
var info = _actions.Any() ? _actions.Dequeue() : null;
if (oldinfo == null) oldinfo = info;
var isLiveUpdate = false;
if (_actions.Any() == false && states.Any() ||
info != null && oldinfo.actionType != info.actionType ||
info != null && oldinfo.stateType != info.stateType) {
if (_actions.Any() == false && states.Any() ||
info != null && oldinfo.actionType != info.actionType ||
info != null && oldinfo.stateType != info.stateType)
{
if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
//最后一个,合起来发送
states.Add(info.state);
info = null;
}
if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType)
{
//最后一个,合起来发送
states.Add(info.state);
info = null;
}
switch (oldinfo.actionType) {
case ExecCommandInfoType.Insert:
await funcInsert();
break;
case ExecCommandInfoType.Delete:
await funcDelete();
break;
}
isLiveUpdate = true;
}
switch (oldinfo.actionType)
{
case ExecCommandInfoType.Insert:
await funcInsert();
break;
case ExecCommandInfoType.Delete:
await funcDelete();
break;
}
isLiveUpdate = true;
}
if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
if (states.Any())
await funcUpdate(isLiveUpdate);
}
if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update)
{
if (states.Any())
await funcUpdate(isLiveUpdate);
}
if (info != null) {
states.Add(info.state);
oldinfo = info;
}
}
isExecCommanding = false;
}
}
if (info != null)
{
states.Add(info.state);
oldinfo = info;
}
}
isExecCommanding = false;
}
}
}

View File

@ -1,10 +1,12 @@

namespace FreeSql {
public class DbContextOptions {
namespace FreeSql
{
public class DbContextOptions
{
/// <summary>
/// 是否开启一对多,联级保存功能
/// </summary>
public bool EnableAddOrUpdateNavigateList { get; set; } = true;
}
/// <summary>
/// 是否开启一对多,联级保存功能
/// </summary>
public bool EnableAddOrUpdateNavigateList { get; set; } = true;
}
}

View File

@ -1,13 +1,16 @@

namespace FreeSql {
public class DbContextOptionsBuilder {
namespace FreeSql
{
public class DbContextOptionsBuilder
{
internal IFreeSql _fsql;
internal IFreeSql _fsql;
public DbContextOptionsBuilder UseFreeSql(IFreeSql orm) {
_fsql = orm;
return this;
}
}
public DbContextOptionsBuilder UseFreeSql(IFreeSql orm)
{
_fsql = orm;
return this;
}
}
}

View File

@ -4,116 +4,134 @@ using System.Linq;
using System.Reflection;
using System.Linq.Expressions;
namespace FreeSql {
partial class DbContext {
namespace FreeSql
{
partial class DbContext
{
public virtual int SaveChanges() {
ExecCommand();
_uow?.Commit();
var ret = _affrows;
_affrows = 0;
return ret;
}
public virtual int SaveChanges()
{
ExecCommand();
_uow?.Commit();
var ret = _affrows;
_affrows = 0;
return ret;
}
static Dictionary<Type, Dictionary<string, Func<object, object[], int>>> _dicExecCommandDbContextBetch = new Dictionary<Type, Dictionary<string, Func<object, object[], int>>>();
bool isExecCommanding = false;
internal void ExecCommand() {
if (isExecCommanding) return;
if (_actions.Any() == false) return;
isExecCommanding = true;
static Dictionary<Type, Dictionary<string, Func<object, object[], int>>> _dicExecCommandDbContextBetch = new Dictionary<Type, Dictionary<string, Func<object, object[], int>>>();
bool isExecCommanding = false;
internal void ExecCommand()
{
if (isExecCommanding) return;
if (_actions.Any() == false) return;
isExecCommanding = true;
ExecCommandInfo oldinfo = null;
var states = new List<object>();
ExecCommandInfo oldinfo = null;
var states = new List<object>();
Func<string, int> dbContextBetch = methodName => {
if (_dicExecCommandDbContextBetch.TryGetValue(oldinfo.stateType, out var trydic) == false)
trydic = new Dictionary<string, Func<object, object[], int>>();
if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
var arrType = oldinfo.stateType.MakeArrayType();
var dbsetType = oldinfo.dbSet.GetType().BaseType;
var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);
Func<string, int> dbContextBetch = methodName =>
{
if (_dicExecCommandDbContextBetch.TryGetValue(oldinfo.stateType, out var trydic) == false)
trydic = new Dictionary<string, Func<object, object[], int>>();
if (trydic.TryGetValue(methodName, out var tryfunc) == false)
{
var arrType = oldinfo.stateType.MakeArrayType();
var dbsetType = oldinfo.dbSet.GetType().BaseType;
var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);
var returnTarget = Expression.Label(typeof(int));
var parm1DbSet = Expression.Parameter(typeof(object));
var parm2Vals = Expression.Parameter(typeof(object[]));
var var1Vals = Expression.Variable(arrType);
tryfunc = Expression.Lambda<Func<object, object[], int>>(Expression.Block(
new[] { var1Vals },
Expression.Assign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
Expression.Label(returnTarget, Expression.Default(typeof(int)))
), new[] { parm1DbSet, parm2Vals }).Compile();
trydic.Add(methodName, tryfunc);
}
return tryfunc(oldinfo.dbSet, states.ToArray());
};
Action funcDelete = () => {
_affrows += dbContextBetch("DbContextBetchRemove");
states.Clear();
};
Action funcInsert = () => {
_affrows += dbContextBetch("DbContextBetchAdd");
states.Clear();
};
Action<bool> funcUpdate = isLiveUpdate => {
var affrows = 0;
if (isLiveUpdate) affrows = dbContextBetch("DbContextBetchUpdateNow");
else affrows = dbContextBetch("DbContextBetchUpdate");
if (affrows == -999) { //最后一个元素已被删除
states.RemoveAt(states.Count - 1);
return;
}
if (affrows == -998 || affrows == -997) { //没有执行更新
var laststate = states[states.Count - 1];
states.Clear();
if (affrows == -997) states.Add(laststate); //保留最后一个
}
if (affrows > 0) {
_affrows += affrows;
var islastNotUpdated = states.Count != affrows;
var laststate = states[states.Count - 1];
states.Clear();
if (islastNotUpdated) states.Add(laststate); //保留最后一个
}
};
var returnTarget = Expression.Label(typeof(int));
var parm1DbSet = Expression.Parameter(typeof(object));
var parm2Vals = Expression.Parameter(typeof(object[]));
var var1Vals = Expression.Variable(arrType);
tryfunc = Expression.Lambda<Func<object, object[], int>>(Expression.Block(
new[] { var1Vals },
Expression.Assign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
Expression.Label(returnTarget, Expression.Default(typeof(int)))
), new[] { parm1DbSet, parm2Vals }).Compile();
trydic.Add(methodName, tryfunc);
}
return tryfunc(oldinfo.dbSet, states.ToArray());
};
Action funcDelete = () =>
{
_affrows += dbContextBetch("DbContextBetchRemove");
states.Clear();
};
Action funcInsert = () =>
{
_affrows += dbContextBetch("DbContextBetchAdd");
states.Clear();
};
Action<bool> funcUpdate = isLiveUpdate =>
{
var affrows = 0;
if (isLiveUpdate) affrows = dbContextBetch("DbContextBetchUpdateNow");
else affrows = dbContextBetch("DbContextBetchUpdate");
if (affrows == -999)
{ //最后一个元素已被删除
states.RemoveAt(states.Count - 1);
return;
}
if (affrows == -998 || affrows == -997)
{ //没有执行更新
var laststate = states[states.Count - 1];
states.Clear();
if (affrows == -997) states.Add(laststate); //保留最后一个
}
if (affrows > 0)
{
_affrows += affrows;
var islastNotUpdated = states.Count != affrows;
var laststate = states[states.Count - 1];
states.Clear();
if (islastNotUpdated) states.Add(laststate); //保留最后一个
}
};
while (_actions.Any() || states.Any()) {
var info = _actions.Any() ? _actions.Dequeue() : null;
if (oldinfo == null) oldinfo = info;
var isLiveUpdate = false;
while (_actions.Any() || states.Any())
{
var info = _actions.Any() ? _actions.Dequeue() : null;
if (oldinfo == null) oldinfo = info;
var isLiveUpdate = false;
if (_actions.Any() == false && states.Any() ||
info != null && oldinfo.actionType != info.actionType ||
info != null && oldinfo.stateType != info.stateType) {
if (_actions.Any() == false && states.Any() ||
info != null && oldinfo.actionType != info.actionType ||
info != null && oldinfo.stateType != info.stateType)
{
if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
//最后一个,合起来发送
states.Add(info.state);
info = null;
}
if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType)
{
//最后一个,合起来发送
states.Add(info.state);
info = null;
}
switch (oldinfo.actionType) {
case ExecCommandInfoType.Insert:
funcInsert();
break;
case ExecCommandInfoType.Delete:
funcDelete();
break;
}
isLiveUpdate = true;
}
switch (oldinfo.actionType)
{
case ExecCommandInfoType.Insert:
funcInsert();
break;
case ExecCommandInfoType.Delete:
funcDelete();
break;
}
isLiveUpdate = true;
}
if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
if (states.Any())
funcUpdate(isLiveUpdate);
}
if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update)
{
if (states.Any())
funcUpdate(isLiveUpdate);
}
if (info != null) {
states.Add(info.state);
oldinfo = info;
}
}
isExecCommanding = false;
}
}
if (info != null)
{
states.Add(info.state);
oldinfo = info;
}
}
isExecCommanding = false;
}
}
}

View File

@ -1,10 +1,13 @@

namespace FreeSql {
public class FreeContext : DbContext {
namespace FreeSql
{
public class FreeContext : DbContext
{
public FreeContext(IFreeSql orm) {
_orm = orm;
}
}
public FreeContext(IFreeSql orm)
{
_orm = orm;
}
}
}

View File

@ -8,274 +8,326 @@ using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace FreeSql {
namespace FreeSql
{
internal class DbContextDbSet<TEntity> : DbSet<TEntity> where TEntity : class {
internal class DbContextDbSet<TEntity> : DbSet<TEntity> where TEntity : class
{
public DbContextDbSet(DbContext ctx) {
_ctx = ctx;
_uow = ctx._uow;
_fsql = ctx._fsql;
}
}
public DbContextDbSet(DbContext ctx)
{
_ctx = ctx;
_uow = ctx._uow;
_fsql = ctx._fsql;
}
}
public interface IDbSet : IDisposable {
Type EntityType { get; }
}
public abstract partial class DbSet<TEntity> : IDbSet where TEntity : class {
public interface IDbSet : IDisposable
{
Type EntityType { get; }
}
public abstract partial class DbSet<TEntity> : IDbSet where TEntity : class
{
internal DbContext _ctx;
internal IUnitOfWork _uow;
internal IFreeSql _fsql;
internal DbContext _ctx;
internal IUnitOfWork _uow;
internal IFreeSql _fsql;
protected virtual ISelect<TEntity> OrmSelect(object dywhere) {
DbContextExecCommand(); //查询前先提交,否则会出脏读
return _fsql.Select<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction(false)).TrackToList(TrackToList).WhereDynamic(dywhere);
}
protected virtual ISelect<TEntity> OrmSelect(object dywhere)
{
DbContextExecCommand(); //查询前先提交,否则会出脏读
return _fsql.Select<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction(false)).TrackToList(TrackToList).WhereDynamic(dywhere);
}
~DbSet() {
this.Dispose();
}
bool _isdisposed = false;
public void Dispose() {
if (_isdisposed) return;
try {
this._dicUpdateTimes.Clear();
this._states.Clear();
} finally {
_isdisposed = true;
GC.SuppressFinalize(this);
}
}
~DbSet()
{
this.Dispose();
}
bool _isdisposed = false;
public void Dispose()
{
if (_isdisposed) return;
try
{
this._dicUpdateTimes.Clear();
this._states.Clear();
}
finally
{
_isdisposed = true;
GC.SuppressFinalize(this);
}
}
protected virtual IInsert<TEntity> OrmInsert() => _fsql.Insert<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction());
protected virtual IInsert<TEntity> OrmInsert(TEntity data) => _fsql.Insert<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).AppendData(data);
protected virtual IInsert<TEntity> OrmInsert(IEnumerable<TEntity> data) => _fsql.Insert<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).AppendData(data);
protected virtual IInsert<TEntity> OrmInsert() => _fsql.Insert<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction());
protected virtual IInsert<TEntity> OrmInsert(TEntity data) => _fsql.Insert<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).AppendData(data);
protected virtual IInsert<TEntity> OrmInsert(IEnumerable<TEntity> data) => _fsql.Insert<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).AppendData(data);
protected virtual IUpdate<TEntity> OrmUpdate(IEnumerable<TEntity> entitys) => _fsql.Update<TEntity>().AsType(_entityType).SetSource(entitys).WithTransaction(_uow?.GetOrBeginTransaction());
protected virtual IDelete<TEntity> OrmDelete(object dywhere) => _fsql.Delete<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).WhereDynamic(dywhere);
protected virtual IUpdate<TEntity> OrmUpdate(IEnumerable<TEntity> entitys) => _fsql.Update<TEntity>().AsType(_entityType).SetSource(entitys).WithTransaction(_uow?.GetOrBeginTransaction());
protected virtual IDelete<TEntity> OrmDelete(object dywhere) => _fsql.Delete<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).WhereDynamic(dywhere);
internal void EnqueueToDbContext(DbContext.ExecCommandInfoType actionType, EntityState state) {
_ctx.EnqueueAction(actionType, this, typeof(EntityState), state);
}
internal void IncrAffrows(int affrows) {
_ctx._affrows += affrows;
}
internal void EnqueueToDbContext(DbContext.ExecCommandInfoType actionType, EntityState state)
{
_ctx.EnqueueAction(actionType, this, typeof(EntityState), state);
}
internal void IncrAffrows(int affrows)
{
_ctx._affrows += affrows;
}
internal void TrackToList(object list) {
if (list == null) return;
var ls = list as IList<TEntity>;
if (ls == null) {
var ie = list as IEnumerable;
if (ie == null) return;
foreach (var item in ie) {
if (item == null) return;
var itemType = item.GetType();
if (itemType == typeof(object)) return;
if (itemType.FullName.StartsWith("Submission#")) itemType = itemType.BaseType;
var dbset = _ctx.Set(itemType);
dbset?.GetType().GetMethod("TrackToList", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(dbset, new object[] { list });
return;
}
return;
}
internal void TrackToList(object list)
{
if (list == null) return;
var ls = list as IList<TEntity>;
if (ls == null)
{
var ie = list as IEnumerable;
if (ie == null) return;
foreach (var item in ie)
{
if (item == null) return;
var itemType = item.GetType();
if (itemType == typeof(object)) return;
if (itemType.FullName.StartsWith("Submission#")) itemType = itemType.BaseType;
var dbset = _ctx.Set(itemType);
dbset?.GetType().GetMethod("TrackToList", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(dbset, new object[] { list });
return;
}
return;
}
foreach (var item in ls) {
var key = _fsql.GetEntityKeyString(_entityType, item, false);
if (key == null) continue;
_states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) => {
_fsql.MapEntityValue(_entityType, item, ov.Value);
ov.Time = DateTime.Now;
return ov;
});
}
}
foreach (var item in ls)
{
var key = _fsql.GetEntityKeyString(_entityType, item, false);
if (key == null) continue;
_states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) =>
{
_fsql.MapEntityValue(_entityType, item, ov.Value);
ov.Time = DateTime.Now;
return ov;
});
}
}
public ISelect<TEntity> Select => this.OrmSelect(null);
public ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => this.OrmSelect(null).Where(exp);
public ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp) => this.OrmSelect(null).WhereIf(condition, exp);
public ISelect<TEntity> Select => this.OrmSelect(null);
public ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => this.OrmSelect(null).Where(exp);
public ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp) => this.OrmSelect(null).WhereIf(condition, exp);
protected ConcurrentDictionary<string, EntityState> _states = new ConcurrentDictionary<string, EntityState>();
internal ConcurrentDictionary<string, EntityState> _statesInternal => _states;
TableInfo _tablePriv;
protected TableInfo _table => _tablePriv ?? (_tablePriv = _fsql.CodeFirst.GetTableByEntity(_entityType));
ColumnInfo[] _tableIdentitysPriv;
protected ColumnInfo[] _tableIdentitys => _tableIdentitysPriv ?? (_tableIdentitysPriv = _table.Primarys.Where(a => a.Attribute.IsIdentity).ToArray());
protected Type _entityType = typeof(TEntity);
public Type EntityType => _entityType;
protected ConcurrentDictionary<string, EntityState> _states = new ConcurrentDictionary<string, EntityState>();
internal ConcurrentDictionary<string, EntityState> _statesInternal => _states;
TableInfo _tablePriv;
protected TableInfo _table => _tablePriv ?? (_tablePriv = _fsql.CodeFirst.GetTableByEntity(_entityType));
ColumnInfo[] _tableIdentitysPriv;
protected ColumnInfo[] _tableIdentitys => _tableIdentitysPriv ?? (_tableIdentitysPriv = _table.Primarys.Where(a => a.Attribute.IsIdentity).ToArray());
protected Type _entityType = typeof(TEntity);
public Type EntityType => _entityType;
/// <summary>
/// 动态Type在使用 DbSet&lt;object&gt; 后使用本方法,指定实体类型
/// </summary>
/// <param name="entityType"></param>
/// <returns></returns>
public void AsType(Type entityType) {
if (entityType == typeof(object)) throw new Exception("ISelect.AsType 参数不支持指定为 object");
if (entityType == _entityType) return;
var newtb = _fsql.CodeFirst.GetTableByEntity(entityType);
_entityType = entityType;
_tablePriv = newtb ?? throw new Exception("DbSet.AsType 参数错误,请传入正确的实体类型");
_tableIdentitysPriv = null;
}
/// <summary>
/// 动态Type在使用 DbSet&lt;object&gt; 后使用本方法,指定实体类型
/// </summary>
/// <param name="entityType"></param>
/// <returns></returns>
public void AsType(Type entityType)
{
if (entityType == typeof(object)) throw new Exception("ISelect.AsType 参数不支持指定为 object");
if (entityType == _entityType) return;
var newtb = _fsql.CodeFirst.GetTableByEntity(entityType);
_entityType = entityType;
_tablePriv = newtb ?? throw new Exception("DbSet.AsType 参数错误,请传入正确的实体类型");
_tableIdentitysPriv = null;
}
public class EntityState {
public EntityState(TEntity value, string key) {
this.Value = value;
this.Key = key;
this.Time = DateTime.Now;
}
public TEntity OldValue { get; set; }
public TEntity Value { get; set; }
public string Key { get; set; }
public DateTime Time { get; set; }
}
/// <summary>
/// 附加实体,可用于不查询就更新或删除
/// </summary>
/// <param name="data"></param>
public void Attach(TEntity data) => AttachRange(new[] { data });
public void AttachRange(IEnumerable<TEntity> data) {
if (data == null || data.Any() == false) return;
if (_table.Primarys.Any() == false) throw new Exception($"不可附加,实体没有主键:{_fsql.GetEntityString(_entityType, data.First())}");
foreach (var item in data) {
var key = _fsql.GetEntityKeyString(_entityType, item, false);
if (string.IsNullOrEmpty(key)) throw new Exception($"不可附加,未设置主键的值:{_fsql.GetEntityString(_entityType, item)}");
public class EntityState
{
public EntityState(TEntity value, string key)
{
this.Value = value;
this.Key = key;
this.Time = DateTime.Now;
}
public TEntity OldValue { get; set; }
public TEntity Value { get; set; }
public string Key { get; set; }
public DateTime Time { get; set; }
}
/// <summary>
/// 附加实体,可用于不查询就更新或删除
/// </summary>
/// <param name="data"></param>
public void Attach(TEntity data) => AttachRange(new[] { data });
public void AttachRange(IEnumerable<TEntity> data)
{
if (data == null || data.Any() == false) return;
if (_table.Primarys.Any() == false) throw new Exception($"不可附加,实体没有主键:{_fsql.GetEntityString(_entityType, data.First())}");
foreach (var item in data)
{
var key = _fsql.GetEntityKeyString(_entityType, item, false);
if (string.IsNullOrEmpty(key)) throw new Exception($"不可附加,未设置主键的值:{_fsql.GetEntityString(_entityType, item)}");
_states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) => {
_fsql.MapEntityValue(_entityType, item, ov.Value);
ov.Time = DateTime.Now;
return ov;
});
}
}
/// <summary>
/// 清空状态数据
/// </summary>
public void FlushState() {
_states.Clear();
}
_states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) =>
{
_fsql.MapEntityValue(_entityType, item, ov.Value);
ov.Time = DateTime.Now;
return ov;
});
}
}
/// <summary>
/// 清空状态数据
/// </summary>
public void FlushState()
{
_states.Clear();
}
#region Utils
EntityState CreateEntityState(TEntity data) {
if (data == null) throw new ArgumentNullException(nameof(data));
var key = _fsql.GetEntityKeyString(_entityType, data, false);
var state = new EntityState((TEntity)Activator.CreateInstance(_entityType), key);
_fsql.MapEntityValue(_entityType, data, state.Value);
return state;
}
bool? ExistsInStates(TEntity data) {
if (data == null) throw new ArgumentNullException(nameof(data));
var key = _fsql.GetEntityKeyString(_entityType, data, false);
if (string.IsNullOrEmpty(key)) return null;
return _states.ContainsKey(key);
}
#region Utils
EntityState CreateEntityState(TEntity data)
{
if (data == null) throw new ArgumentNullException(nameof(data));
var key = _fsql.GetEntityKeyString(_entityType, data, false);
var state = new EntityState((TEntity)Activator.CreateInstance(_entityType), key);
_fsql.MapEntityValue(_entityType, data, state.Value);
return state;
}
bool? ExistsInStates(TEntity data)
{
if (data == null) throw new ArgumentNullException(nameof(data));
var key = _fsql.GetEntityKeyString(_entityType, data, false);
if (string.IsNullOrEmpty(key)) return null;
return _states.ContainsKey(key);
}
bool CanAdd(IEnumerable<TEntity> data, bool isThrow) {
if (data == null) {
if (isThrow) throw new ArgumentNullException(nameof(data));
return false;
}
if (data.Any() == false) return false;
foreach (var s in data) if (CanAdd(s, isThrow) == false) return false;
return true;
}
bool CanAdd(TEntity data, bool isThrow) {
if (data == null) {
if (isThrow) throw new ArgumentNullException(nameof(data));
return false;
}
if (_table.Primarys.Any() == false) {
if (isThrow) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
var key = _fsql.GetEntityKeyString(_entityType, data, true);
if (string.IsNullOrEmpty(key)) {
switch (_fsql.Ado.DataType) {
case DataType.SqlServer:
case DataType.PostgreSQL:
return true;
case DataType.MySql:
case DataType.Oracle:
case DataType.Sqlite:
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) {
return true;
}
if (isThrow) throw new Exception($"不可添加,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
} else {
if (_states.ContainsKey(key)) {
if (isThrow) throw new Exception($"不可添加,已存在于状态管理:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
var idval = _fsql.GetEntityIdentityValueWithPrimary(_entityType, data);
if (idval > 0) {
if (isThrow) throw new Exception($"不可添加,自增属性有值:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
}
return true;
}
bool CanAdd(IEnumerable<TEntity> data, bool isThrow)
{
if (data == null)
{
if (isThrow) throw new ArgumentNullException(nameof(data));
return false;
}
if (data.Any() == false) return false;
foreach (var s in data) if (CanAdd(s, isThrow) == false) return false;
return true;
}
bool CanAdd(TEntity data, bool isThrow)
{
if (data == null)
{
if (isThrow) throw new ArgumentNullException(nameof(data));
return false;
}
if (_table.Primarys.Any() == false)
{
if (isThrow) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
var key = _fsql.GetEntityKeyString(_entityType, data, true);
if (string.IsNullOrEmpty(key))
{
switch (_fsql.Ado.DataType)
{
case DataType.SqlServer:
case DataType.PostgreSQL:
return true;
case DataType.MySql:
case DataType.Oracle:
case DataType.Sqlite:
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1)
{
return true;
}
if (isThrow) throw new Exception($"不可添加,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
}
else
{
if (_states.ContainsKey(key))
{
if (isThrow) throw new Exception($"不可添加,已存在于状态管理:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
var idval = _fsql.GetEntityIdentityValueWithPrimary(_entityType, data);
if (idval > 0)
{
if (isThrow) throw new Exception($"不可添加,自增属性有值:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
}
return true;
}
bool CanUpdate(IEnumerable<TEntity> data, bool isThrow) {
if (data == null) {
if (isThrow) throw new ArgumentNullException(nameof(data));
return false;
}
if (data.Any() == false) return false;
foreach (var s in data) if (CanUpdate(s, isThrow) == false) return false;
return true;
}
bool CanUpdate(TEntity data, bool isThrow) {
if (data == null) {
if (isThrow) throw new ArgumentNullException(nameof(data));
return false;
}
if (_table.Primarys.Any() == false) {
if (isThrow) throw new Exception($"不可更新,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
var key = _fsql.GetEntityKeyString(_entityType, data, false);
if (string.IsNullOrEmpty(key)) {
if (isThrow) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
if (_states.TryGetValue(key, out var tryval) == false) {
if (isThrow) throw new Exception($"不可更新,数据未被跟踪,应该先查询 或者 Attach{_fsql.GetEntityString(_entityType, data)}");
return false;
}
return true;
}
bool CanUpdate(IEnumerable<TEntity> data, bool isThrow)
{
if (data == null)
{
if (isThrow) throw new ArgumentNullException(nameof(data));
return false;
}
if (data.Any() == false) return false;
foreach (var s in data) if (CanUpdate(s, isThrow) == false) return false;
return true;
}
bool CanUpdate(TEntity data, bool isThrow)
{
if (data == null)
{
if (isThrow) throw new ArgumentNullException(nameof(data));
return false;
}
if (_table.Primarys.Any() == false)
{
if (isThrow) throw new Exception($"不可更新,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
var key = _fsql.GetEntityKeyString(_entityType, data, false);
if (string.IsNullOrEmpty(key))
{
if (isThrow) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
if (_states.TryGetValue(key, out var tryval) == false)
{
if (isThrow) throw new Exception($"不可更新,数据未被跟踪,应该先查询 或者 Attach{_fsql.GetEntityString(_entityType, data)}");
return false;
}
return true;
}
bool CanRemove(IEnumerable<TEntity> data, bool isThrow) {
if (data == null) {
if (isThrow) throw new ArgumentNullException(nameof(data));
return false;
}
if (data.Any() == false) return false;
foreach (var s in data) if (CanRemove(s, isThrow) == false) return false;
return true;
}
bool CanRemove(TEntity data, bool isThrow) {
if (data == null) {
if (isThrow) throw new ArgumentNullException(nameof(data));
return false;
}
if (_table.Primarys.Any() == false) {
if (isThrow) throw new Exception($"不可删除,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
var key = _fsql.GetEntityKeyString(_entityType, data, false);
if (string.IsNullOrEmpty(key)) {
if (isThrow) throw new Exception($"不可删除,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
//if (_states.TryGetValue(key, out var tryval) == false) {
// if (isThrow) throw new Exception($"不可删除,数据未被跟踪,应该先查询:{_fsql.GetEntityString(_entityType, data)}");
// return false;
//}
return true;
}
#endregion
}
bool CanRemove(IEnumerable<TEntity> data, bool isThrow)
{
if (data == null)
{
if (isThrow) throw new ArgumentNullException(nameof(data));
return false;
}
if (data.Any() == false) return false;
foreach (var s in data) if (CanRemove(s, isThrow) == false) return false;
return true;
}
bool CanRemove(TEntity data, bool isThrow)
{
if (data == null)
{
if (isThrow) throw new ArgumentNullException(nameof(data));
return false;
}
if (_table.Primarys.Any() == false)
{
if (isThrow) throw new Exception($"不可删除,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
var key = _fsql.GetEntityKeyString(_entityType, data, false);
if (string.IsNullOrEmpty(key))
{
if (isThrow) throw new Exception($"不可删除,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
return false;
}
//if (_states.TryGetValue(key, out var tryval) == false) {
// if (isThrow) throw new Exception($"不可删除,数据未被跟踪,应该先查询:{_fsql.GetEntityString(_entityType, data)}");
// return false;
//}
return true;
}
#endregion
}
}

View File

@ -6,263 +6,303 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FreeSql {
partial class DbSet<TEntity> {
namespace FreeSql
{
partial class DbSet<TEntity>
{
Task DbContextExecCommandAsync() {
_dicUpdateTimes.Clear();
return _ctx.ExecCommandAsync();
}
Task DbContextExecCommandAsync()
{
_dicUpdateTimes.Clear();
return _ctx.ExecCommandAsync();
}
async Task<int> DbContextBetchAddAsync(EntityState[] adds) {
if (adds.Any() == false) return 0;
var affrows = await this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrowsAsync();
return affrows;
}
async Task<int> DbContextBetchAddAsync(EntityState[] adds)
{
if (adds.Any() == false) return 0;
var affrows = await this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrowsAsync();
return affrows;
}
#region Add
async Task AddPrivAsync(TEntity data, bool isCheck) {
if (isCheck && CanAdd(data, true) == false) return;
if (_tableIdentitys.Length > 0) {
//有自增,马上执行
switch (_fsql.Ado.DataType) {
case DataType.SqlServer:
case DataType.PostgreSQL:
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) {
await DbContextExecCommandAsync();
var idtval = await this.OrmInsert(data).ExecuteIdentityAsync();
IncrAffrows(1);
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
Attach(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
await AddOrUpdateNavigateListAsync(data);
} else {
await DbContextExecCommandAsync();
var newval = (await this.OrmInsert(data).ExecuteInsertedAsync()).First();
IncrAffrows(1);
_fsql.MapEntityValue(_entityType, newval, data);
Attach(newval);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
await AddOrUpdateNavigateListAsync(data);
}
return;
case DataType.MySql:
case DataType.Oracle:
case DataType.Sqlite:
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) {
await DbContextExecCommandAsync();
var idtval = await this.OrmInsert(data).ExecuteIdentityAsync();
IncrAffrows(1);
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
Attach(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
await AddOrUpdateNavigateListAsync(data);
}
return;
}
}
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data));
Attach(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
await AddOrUpdateNavigateListAsync(data);
}
public Task AddAsync(TEntity data) => AddPrivAsync(data, true);
async public Task AddRangeAsync(IEnumerable<TEntity> data) {
if (CanAdd(data, true) == false) return;
if (data.ElementAtOrDefault(1) == default(TEntity)) {
await AddAsync(data.First());
return;
}
if (_tableIdentitys.Length > 0) {
//有自增,马上执行
switch (_fsql.Ado.DataType) {
case DataType.SqlServer:
case DataType.PostgreSQL:
await DbContextExecCommandAsync();
var rets = await this.OrmInsert(data).ExecuteInsertedAsync();
if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配");
var idx = 0;
foreach (var s in data)
_fsql.MapEntityValue(_entityType, rets[idx++], s);
IncrAffrows(rets.Count);
AttachRange(rets);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
await AddOrUpdateNavigateListAsync(item);
return;
case DataType.MySql:
case DataType.Oracle:
case DataType.Sqlite:
foreach (var s in data)
await AddPrivAsync(s, false);
return;
}
} else {
//进入队列,等待 SaveChanges 时执行
foreach (var item in data)
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(item));
AttachRange(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
await AddOrUpdateNavigateListAsync(item);
}
}
async Task AddOrUpdateNavigateListAsync(TEntity item) {
Type itemType = null;
foreach (var prop in _table.Properties) {
if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;
var tref = _table.GetTableRef(prop.Key, true);
if (tref == null) continue;
#region Add
async Task AddPrivAsync(TEntity data, bool isCheck)
{
if (isCheck && CanAdd(data, true) == false) return;
if (_tableIdentitys.Length > 0)
{
//有自增,马上执行
switch (_fsql.Ado.DataType)
{
case DataType.SqlServer:
case DataType.PostgreSQL:
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1)
{
await DbContextExecCommandAsync();
var idtval = await this.OrmInsert(data).ExecuteIdentityAsync();
IncrAffrows(1);
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
Attach(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
await AddOrUpdateNavigateListAsync(data);
}
else
{
await DbContextExecCommandAsync();
var newval = (await this.OrmInsert(data).ExecuteInsertedAsync()).First();
IncrAffrows(1);
_fsql.MapEntityValue(_entityType, newval, data);
Attach(newval);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
await AddOrUpdateNavigateListAsync(data);
}
return;
case DataType.MySql:
case DataType.Oracle:
case DataType.Sqlite:
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1)
{
await DbContextExecCommandAsync();
var idtval = await this.OrmInsert(data).ExecuteIdentityAsync();
IncrAffrows(1);
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
Attach(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
await AddOrUpdateNavigateListAsync(data);
}
return;
}
}
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data));
Attach(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
await AddOrUpdateNavigateListAsync(data);
}
public Task AddAsync(TEntity data) => AddPrivAsync(data, true);
async public Task AddRangeAsync(IEnumerable<TEntity> data)
{
if (CanAdd(data, true) == false) return;
if (data.ElementAtOrDefault(1) == default(TEntity))
{
await AddAsync(data.First());
return;
}
if (_tableIdentitys.Length > 0)
{
//有自增,马上执行
switch (_fsql.Ado.DataType)
{
case DataType.SqlServer:
case DataType.PostgreSQL:
await DbContextExecCommandAsync();
var rets = await this.OrmInsert(data).ExecuteInsertedAsync();
if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配");
var idx = 0;
foreach (var s in data)
_fsql.MapEntityValue(_entityType, rets[idx++], s);
IncrAffrows(rets.Count);
AttachRange(rets);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
await AddOrUpdateNavigateListAsync(item);
return;
case DataType.MySql:
case DataType.Oracle:
case DataType.Sqlite:
foreach (var s in data)
await AddPrivAsync(s, false);
return;
}
}
else
{
//进入队列,等待 SaveChanges 时执行
foreach (var item in data)
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(item));
AttachRange(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
await AddOrUpdateNavigateListAsync(item);
}
}
async Task AddOrUpdateNavigateListAsync(TEntity item)
{
Type itemType = null;
foreach (var prop in _table.Properties)
{
if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;
var tref = _table.GetTableRef(prop.Key, true);
if (tref == null) continue;
switch (tref.RefType) {
case Internal.Model.TableRefType.OneToOne:
case Internal.Model.TableRefType.ManyToOne:
case Internal.Model.TableRefType.ManyToMany:
continue;
case Internal.Model.TableRefType.OneToMany:
if (itemType == null) itemType = item.GetType();
if (_table.TypeLazy != null && itemType == _table.TypeLazy) {
var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, System.Reflection.FieldInfo>()).GetOrAdd(prop.Key, propName =>
_table.TypeLazy.GetField($"__lazy__{propName}", System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance));
if (lazyField != null) {
var lazyFieldValue = (bool)lazyField.GetValue(item);
if (lazyFieldValue == false) continue;
}
}
var propVal = prop.Value.GetValue(item);
var propValEach = propVal as IEnumerable;
if (propValEach == null) continue;
object dbset = null;
System.Reflection.MethodInfo dbsetAddOrUpdate = null;
foreach (var propValItem in propValEach) {
if (dbset == null) {
dbset = _ctx.Set(tref.RefEntityType);
dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdateAsync", new Type[] { tref.RefEntityType });
}
for (var colidx = 0; colidx < tref.Columns.Count; colidx++) {
tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
}
Task task = dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem }) as Task;
await task;
}
break;
}
}
}
#endregion
switch (tref.RefType)
{
case Internal.Model.TableRefType.OneToOne:
case Internal.Model.TableRefType.ManyToOne:
case Internal.Model.TableRefType.ManyToMany:
continue;
case Internal.Model.TableRefType.OneToMany:
if (itemType == null) itemType = item.GetType();
if (_table.TypeLazy != null && itemType == _table.TypeLazy)
{
var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, System.Reflection.FieldInfo>()).GetOrAdd(prop.Key, propName =>
_table.TypeLazy.GetField($"__lazy__{propName}", System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance));
if (lazyField != null)
{
var lazyFieldValue = (bool)lazyField.GetValue(item);
if (lazyFieldValue == false) continue;
}
}
var propVal = prop.Value.GetValue(item);
var propValEach = propVal as IEnumerable;
if (propValEach == null) continue;
object dbset = null;
System.Reflection.MethodInfo dbsetAddOrUpdate = null;
foreach (var propValItem in propValEach)
{
if (dbset == null)
{
dbset = _ctx.Set(tref.RefEntityType);
dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdateAsync", new Type[] { tref.RefEntityType });
}
for (var colidx = 0; colidx < tref.Columns.Count; colidx++)
{
tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
}
Task task = dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem }) as Task;
await task;
}
break;
}
}
}
#endregion
#region UpdateAsync
Task<int> DbContextBetchUpdateAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, false);
Task<int> DbContextBetchUpdateNowAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, true);
async Task<int> DbContextBetchUpdatePrivAsync(EntityState[] ups, bool isLiveUpdate) {
if (ups.Any() == false) return 0;
var uplst1 = ups[ups.Length - 1];
var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;
#region UpdateAsync
Task<int> DbContextBetchUpdateAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, false);
Task<int> DbContextBetchUpdateNowAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, true);
async Task<int> DbContextBetchUpdatePrivAsync(EntityState[] ups, bool isLiveUpdate)
{
if (ups.Any() == false) return 0;
var uplst1 = ups[ups.Length - 1];
var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;
if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
var lstval2 = default(EntityState);
if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEntityString(_entityType, uplst2.Value)}");
if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
var lstval2 = default(EntityState);
if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEntityString(_entityType, uplst2.Value)}");
var cuig1 = _fsql.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true);
var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null;
var cuig1 = _fsql.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true);
var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null;
List<EntityState> data = null;
string[] cuig = null;
if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) {
//最后一个不保存
data = ups.ToList();
data.RemoveAt(ups.Length - 1);
cuig = cuig2;
} else if (isLiveUpdate) {
//立即保存
data = ups.ToList();
cuig = cuig1;
}
List<EntityState> data = null;
string[] cuig = null;
if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0)
{
//最后一个不保存
data = ups.ToList();
data.RemoveAt(ups.Length - 1);
cuig = cuig2;
}
else if (isLiveUpdate)
{
//立即保存
data = ups.ToList();
cuig = cuig1;
}
if (data?.Count > 0) {
if (data?.Count > 0)
{
if (cuig.Length == _table.Columns.Count)
return ups.Length == data.Count ? -998 : -997;
if (cuig.Length == _table.Columns.Count)
return ups.Length == data.Count ? -998 : -997;
var updateSource = data.Select(a => a.Value).ToArray();
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
var updateSource = data.Select(a => a.Value).ToArray();
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
var affrows = await update.ExecuteAffrowsAsync();
var affrows = await update.ExecuteAffrowsAsync();
foreach (var newval in data) {
if (_states.TryGetValue(newval.Key, out var tryold))
_fsql.MapEntityValue(_entityType, newval.Value, tryold.Value);
if (newval.OldValue != null)
_fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue);
}
return affrows;
}
foreach (var newval in data)
{
if (_states.TryGetValue(newval.Key, out var tryold))
_fsql.MapEntityValue(_entityType, newval.Value, tryold.Value);
if (newval.OldValue != null)
_fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue);
}
return affrows;
}
//等待下次对比再保存
return 0;
}
async public Task UpdateAsync(TEntity data) {
var exists = ExistsInStates(data);
if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
if (exists == false) {
var olddata = await OrmSelect(data).FirstAsync();
if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}");
}
//等待下次对比再保存
return 0;
}
async public Task UpdateAsync(TEntity data)
{
var exists = ExistsInStates(data);
if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
if (exists == false)
{
var olddata = await OrmSelect(data).FirstAsync();
if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}");
}
await UpdateRangePrivAsync(new[] { data }, true);
}
public Task UpdateRangeAsync(IEnumerable<TEntity> data) => UpdateRangePrivAsync(data, true);
async Task UpdateRangePrivAsync(IEnumerable<TEntity> data, bool isCheck) {
if (CanUpdate(data, true) == false) return;
foreach (var item in data) {
if (_dicUpdateTimes.ContainsKey(item))
await DbContextExecCommandAsync();
_dicUpdateTimes.Add(item, 1);
await UpdateRangePrivAsync(new[] { data }, true);
}
public Task UpdateRangeAsync(IEnumerable<TEntity> data) => UpdateRangePrivAsync(data, true);
async Task UpdateRangePrivAsync(IEnumerable<TEntity> data, bool isCheck)
{
if (CanUpdate(data, true) == false) return;
foreach (var item in data)
{
if (_dicUpdateTimes.ContainsKey(item))
await DbContextExecCommandAsync();
_dicUpdateTimes.Add(item, 1);
var state = CreateEntityState(item);
state.OldValue = item;
EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state);
}
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
await AddOrUpdateNavigateListAsync(item);
}
#endregion
var state = CreateEntityState(item);
state.OldValue = item;
EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state);
}
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
await AddOrUpdateNavigateListAsync(item);
}
#endregion
#region RemoveAsync
async Task<int> DbContextBetchRemoveAsync(EntityState[] dels) {
if (dels.Any() == false) return 0;
var affrows = await this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrowsAsync();
return Math.Max(dels.Length, affrows);
}
#endregion
#region RemoveAsync
async Task<int> DbContextBetchRemoveAsync(EntityState[] dels)
{
if (dels.Any() == false) return 0;
var affrows = await this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrowsAsync();
return Math.Max(dels.Length, affrows);
}
#endregion
#region AddOrUpdateAsync
async public Task AddOrUpdateAsync(TEntity data) {
if (data == null) throw new ArgumentNullException(nameof(data));
if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
#region AddOrUpdateAsync
async public Task AddOrUpdateAsync(TEntity data)
{
if (data == null) throw new ArgumentNullException(nameof(data));
if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
var flagExists = ExistsInStates(data);
if (flagExists == false) {
var olddata = await OrmSelect(data).FirstAsync();
if (olddata == null) flagExists = false;
}
var flagExists = ExistsInStates(data);
if (flagExists == false)
{
var olddata = await OrmSelect(data).FirstAsync();
if (olddata == null) flagExists = false;
}
if (flagExists == true && CanUpdate(data, false)) {
await DbContextExecCommandAsync();
var affrows = _ctx._affrows;
await UpdateRangePrivAsync(new[] { data }, false);
await DbContextExecCommandAsync();
affrows = _ctx._affrows - affrows;
if (affrows > 0) return;
}
if (CanAdd(data, false)) {
_fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data);
await AddPrivAsync(data, false);
}
}
#endregion
}
if (flagExists == true && CanUpdate(data, false))
{
await DbContextExecCommandAsync();
var affrows = _ctx._affrows;
await UpdateRangePrivAsync(new[] { data }, false);
await DbContextExecCommandAsync();
affrows = _ctx._affrows - affrows;
if (affrows > 0) return;
}
if (CanAdd(data, false))
{
_fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data);
await AddPrivAsync(data, false);
}
}
#endregion
}
}

View File

@ -6,300 +6,344 @@ using System.Collections.Concurrent;
using System.Linq;
using System.Reflection;
namespace FreeSql {
partial class DbSet<TEntity> {
namespace FreeSql
{
partial class DbSet<TEntity>
{
void DbContextExecCommand() {
_dicUpdateTimes.Clear();
_ctx.ExecCommand();
}
void DbContextExecCommand()
{
_dicUpdateTimes.Clear();
_ctx.ExecCommand();
}
int DbContextBetchAdd(EntityState[] adds) {
if (adds.Any() == false) return 0;
var affrows = this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrows();
return affrows;
}
int DbContextBetchAdd(EntityState[] adds)
{
if (adds.Any() == false) return 0;
var affrows = this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrows();
return affrows;
}
#region Add
void AddPriv(TEntity data, bool isCheck) {
if (isCheck && CanAdd(data, true) == false) return;
if (_tableIdentitys.Length > 0) {
//有自增,马上执行
switch (_fsql.Ado.DataType) {
case DataType.SqlServer:
case DataType.PostgreSQL:
if (_tableIdentitys.Length == 1) {
DbContextExecCommand();
var idtval = this.OrmInsert(data).ExecuteIdentity();
IncrAffrows(1);
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
Attach(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
AddOrUpdateNavigateList(data);
} else {
DbContextExecCommand();
var newval = this.OrmInsert(data).ExecuteInserted().First();
IncrAffrows(1);
_fsql.MapEntityValue(_entityType, newval, data);
Attach(newval);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
AddOrUpdateNavigateList(data);
}
return;
case DataType.MySql:
case DataType.Oracle:
case DataType.Sqlite:
if (_tableIdentitys.Length == 1) {
DbContextExecCommand();
var idtval = this.OrmInsert(data).ExecuteIdentity();
IncrAffrows(1);
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
Attach(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
AddOrUpdateNavigateList(data);
}
return;
}
}
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data));
Attach(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
AddOrUpdateNavigateList(data);
}
/// <summary>
/// 添加
/// </summary>
/// <param name="data"></param>
public void Add(TEntity data) => AddPriv(data, true);
public void AddRange(IEnumerable<TEntity> data) {
if (CanAdd(data, true) == false) return;
if (data.ElementAtOrDefault(1) == default(TEntity)) {
Add(data.First());
return;
}
if (_tableIdentitys.Length > 0) {
//有自增,马上执行
switch (_fsql.Ado.DataType) {
case DataType.SqlServer:
case DataType.PostgreSQL:
DbContextExecCommand();
var rets = this.OrmInsert(data).ExecuteInserted();
if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配");
var idx = 0;
foreach (var s in data)
_fsql.MapEntityValue(_entityType, rets[idx++], s);
IncrAffrows(rets.Count);
AttachRange(rets);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
AddOrUpdateNavigateList(item);
return;
case DataType.MySql:
case DataType.Oracle:
case DataType.Sqlite:
foreach (var s in data)
AddPriv(s, false);
return;
}
} else {
//进入队列,等待 SaveChanges 时执行
foreach (var item in data)
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(item));
AttachRange(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
AddOrUpdateNavigateList(item);
}
}
static ConcurrentDictionary<Type, ConcurrentDictionary<string, FieldInfo>> _dicLazyIsSetField = new ConcurrentDictionary<Type, ConcurrentDictionary<string, FieldInfo>>();
void AddOrUpdateNavigateList(TEntity item) {
Type itemType = null;
foreach (var prop in _table.Properties) {
if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;
#region Add
void AddPriv(TEntity data, bool isCheck)
{
if (isCheck && CanAdd(data, true) == false) return;
if (_tableIdentitys.Length > 0)
{
//有自增,马上执行
switch (_fsql.Ado.DataType)
{
case DataType.SqlServer:
case DataType.PostgreSQL:
if (_tableIdentitys.Length == 1)
{
DbContextExecCommand();
var idtval = this.OrmInsert(data).ExecuteIdentity();
IncrAffrows(1);
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
Attach(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
AddOrUpdateNavigateList(data);
}
else
{
DbContextExecCommand();
var newval = this.OrmInsert(data).ExecuteInserted().First();
IncrAffrows(1);
_fsql.MapEntityValue(_entityType, newval, data);
Attach(newval);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
AddOrUpdateNavigateList(data);
}
return;
case DataType.MySql:
case DataType.Oracle:
case DataType.Sqlite:
if (_tableIdentitys.Length == 1)
{
DbContextExecCommand();
var idtval = this.OrmInsert(data).ExecuteIdentity();
IncrAffrows(1);
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
Attach(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
AddOrUpdateNavigateList(data);
}
return;
}
}
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data));
Attach(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
AddOrUpdateNavigateList(data);
}
/// <summary>
/// 添加
/// </summary>
/// <param name="data"></param>
public void Add(TEntity data) => AddPriv(data, true);
public void AddRange(IEnumerable<TEntity> data)
{
if (CanAdd(data, true) == false) return;
if (data.ElementAtOrDefault(1) == default(TEntity))
{
Add(data.First());
return;
}
if (_tableIdentitys.Length > 0)
{
//有自增,马上执行
switch (_fsql.Ado.DataType)
{
case DataType.SqlServer:
case DataType.PostgreSQL:
DbContextExecCommand();
var rets = this.OrmInsert(data).ExecuteInserted();
if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配");
var idx = 0;
foreach (var s in data)
_fsql.MapEntityValue(_entityType, rets[idx++], s);
IncrAffrows(rets.Count);
AttachRange(rets);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
AddOrUpdateNavigateList(item);
return;
case DataType.MySql:
case DataType.Oracle:
case DataType.Sqlite:
foreach (var s in data)
AddPriv(s, false);
return;
}
}
else
{
//进入队列,等待 SaveChanges 时执行
foreach (var item in data)
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(item));
AttachRange(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
AddOrUpdateNavigateList(item);
}
}
static ConcurrentDictionary<Type, ConcurrentDictionary<string, FieldInfo>> _dicLazyIsSetField = new ConcurrentDictionary<Type, ConcurrentDictionary<string, FieldInfo>>();
void AddOrUpdateNavigateList(TEntity item)
{
Type itemType = null;
foreach (var prop in _table.Properties)
{
if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;
object propVal = null;
object propVal = null;
if (itemType == null) itemType = item.GetType();
if (_table.TypeLazy != null && itemType == _table.TypeLazy) {
var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, FieldInfo>()).GetOrAdd(prop.Key, propName =>
_table.TypeLazy.GetField($"__lazy__{propName}", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance));
if (lazyField != null) {
var lazyFieldValue = (bool)lazyField.GetValue(item);
if (lazyFieldValue == false) continue;
}
propVal = prop.Value.GetValue(item);
} else {
propVal = prop.Value.GetValue(item);
if (propVal == null) continue;
}
if (itemType == null) itemType = item.GetType();
if (_table.TypeLazy != null && itemType == _table.TypeLazy)
{
var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, FieldInfo>()).GetOrAdd(prop.Key, propName =>
_table.TypeLazy.GetField($"__lazy__{propName}", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance));
if (lazyField != null)
{
var lazyFieldValue = (bool)lazyField.GetValue(item);
if (lazyFieldValue == false) continue;
}
propVal = prop.Value.GetValue(item);
}
else
{
propVal = prop.Value.GetValue(item);
if (propVal == null) continue;
}
var tref = _table.GetTableRef(prop.Key, true);
if (tref == null) continue;
var tref = _table.GetTableRef(prop.Key, true);
if (tref == null) continue;
switch(tref.RefType) {
case Internal.Model.TableRefType.OneToOne:
case Internal.Model.TableRefType.ManyToOne:
case Internal.Model.TableRefType.ManyToMany:
continue;
case Internal.Model.TableRefType.OneToMany:
var propValEach = propVal as IEnumerable;
if (propValEach == null) continue;
object dbset = null;
MethodInfo dbsetAddOrUpdate = null;
foreach (var propValItem in propValEach) {
if (dbset == null) {
dbset = _ctx.Set(tref.RefEntityType);
dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdate", new Type[] { tref.RefEntityType });
}
for (var colidx = 0; colidx < tref.Columns.Count; colidx++) {
tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
}
dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem });
}
break;
}
}
}
#endregion
switch (tref.RefType)
{
case Internal.Model.TableRefType.OneToOne:
case Internal.Model.TableRefType.ManyToOne:
case Internal.Model.TableRefType.ManyToMany:
continue;
case Internal.Model.TableRefType.OneToMany:
var propValEach = propVal as IEnumerable;
if (propValEach == null) continue;
object dbset = null;
MethodInfo dbsetAddOrUpdate = null;
foreach (var propValItem in propValEach)
{
if (dbset == null)
{
dbset = _ctx.Set(tref.RefEntityType);
dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdate", new Type[] { tref.RefEntityType });
}
for (var colidx = 0; colidx < tref.Columns.Count; colidx++)
{
tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
}
dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem });
}
break;
}
}
}
#endregion
#region Update
int DbContextBetchUpdate(EntityState[] ups) => DbContextBetchUpdatePriv(ups, false);
int DbContextBetchUpdateNow(EntityState[] ups) => DbContextBetchUpdatePriv(ups, true);
int DbContextBetchUpdatePriv(EntityState[] ups, bool isLiveUpdate) {
if (ups.Any() == false) return 0;
var uplst1 = ups[ups.Length - 1];
var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;
#region Update
int DbContextBetchUpdate(EntityState[] ups) => DbContextBetchUpdatePriv(ups, false);
int DbContextBetchUpdateNow(EntityState[] ups) => DbContextBetchUpdatePriv(ups, true);
int DbContextBetchUpdatePriv(EntityState[] ups, bool isLiveUpdate)
{
if (ups.Any() == false) return 0;
var uplst1 = ups[ups.Length - 1];
var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;
if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
var lstval2 = default(EntityState);
if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEntityString(_entityType, uplst2.Value)}");
if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
var lstval2 = default(EntityState);
if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEntityString(_entityType, uplst2.Value)}");
var cuig1 = _fsql.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true);
var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null;
var cuig1 = _fsql.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true);
var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null;
List<EntityState> data = null;
string[] cuig = null;
if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) {
//最后一个不保存
data = ups.ToList();
data.RemoveAt(ups.Length - 1);
cuig = cuig2;
} else if (isLiveUpdate) {
//立即保存
data = ups.ToList();
cuig = cuig1;
}
List<EntityState> data = null;
string[] cuig = null;
if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0)
{
//最后一个不保存
data = ups.ToList();
data.RemoveAt(ups.Length - 1);
cuig = cuig2;
}
else if (isLiveUpdate)
{
//立即保存
data = ups.ToList();
cuig = cuig1;
}
if (data?.Count > 0) {
if (data?.Count > 0)
{
if (cuig.Length == _table.Columns.Count)
return ups.Length == data.Count ? -998 : -997;
if (cuig.Length == _table.Columns.Count)
return ups.Length == data.Count ? -998 : -997;
var updateSource = data.Select(a => a.Value).ToArray();
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
var updateSource = data.Select(a => a.Value).ToArray();
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
var affrows = update.ExecuteAffrows();
var affrows = update.ExecuteAffrows();
foreach (var newval in data) {
if (_states.TryGetValue(newval.Key, out var tryold))
_fsql.MapEntityValue(_entityType, newval.Value, tryold.Value);
if (newval.OldValue != null)
_fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue);
}
return affrows;
}
foreach (var newval in data)
{
if (_states.TryGetValue(newval.Key, out var tryold))
_fsql.MapEntityValue(_entityType, newval.Value, tryold.Value);
if (newval.OldValue != null)
_fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue);
}
return affrows;
}
//等待下次对比再保存
return 0;
}
//等待下次对比再保存
return 0;
}
Dictionary<TEntity, byte> _dicUpdateTimes = new Dictionary<TEntity, byte>();
/// <summary>
/// 更新
/// </summary>
/// <param name="data"></param>
public void Update(TEntity data) {
var exists = ExistsInStates(data);
if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
if (exists == false) {
var olddata = OrmSelect(data).First();
if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}");
}
Dictionary<TEntity, byte> _dicUpdateTimes = new Dictionary<TEntity, byte>();
/// <summary>
/// 更新
/// </summary>
/// <param name="data"></param>
public void Update(TEntity data)
{
var exists = ExistsInStates(data);
if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
if (exists == false)
{
var olddata = OrmSelect(data).First();
if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}");
}
UpdateRangePriv(new[] { data }, true);
}
public void UpdateRange(IEnumerable<TEntity> data) => UpdateRangePriv(data, true);
void UpdateRangePriv(IEnumerable<TEntity> data, bool isCheck) {
if (CanUpdate(data, true) == false) return;
foreach (var item in data) {
if (_dicUpdateTimes.ContainsKey(item))
DbContextExecCommand();
_dicUpdateTimes.Add(item, 1);
UpdateRangePriv(new[] { data }, true);
}
public void UpdateRange(IEnumerable<TEntity> data) => UpdateRangePriv(data, true);
void UpdateRangePriv(IEnumerable<TEntity> data, bool isCheck)
{
if (CanUpdate(data, true) == false) return;
foreach (var item in data)
{
if (_dicUpdateTimes.ContainsKey(item))
DbContextExecCommand();
_dicUpdateTimes.Add(item, 1);
var state = CreateEntityState(item);
state.OldValue = item;
EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state);
}
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
AddOrUpdateNavigateList(item);
}
#endregion
var state = CreateEntityState(item);
state.OldValue = item;
EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state);
}
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
AddOrUpdateNavigateList(item);
}
#endregion
#region Remove
int DbContextBetchRemove(EntityState[] dels) {
if (dels.Any() == false) return 0;
var affrows = this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrows();
return Math.Max(dels.Length, affrows);
}
#region Remove
int DbContextBetchRemove(EntityState[] dels)
{
if (dels.Any() == false) return 0;
var affrows = this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrows();
return Math.Max(dels.Length, affrows);
}
/// <summary>
/// 删除
/// </summary>
/// <param name="data"></param>
public void Remove(TEntity data) => RemoveRange(new[] { data });
public void RemoveRange(IEnumerable<TEntity> data) {
if (CanRemove(data, true) == false) return;
foreach (var item in data) {
var state = CreateEntityState(item);
_states.TryRemove(state.Key, out var trystate);
_fsql.ClearEntityPrimaryValueWithIdentityAndGuid(_entityType, item);
/// <summary>
/// 删除
/// </summary>
/// <param name="data"></param>
public void Remove(TEntity data) => RemoveRange(new[] { data });
public void RemoveRange(IEnumerable<TEntity> data)
{
if (CanRemove(data, true) == false) return;
foreach (var item in data)
{
var state = CreateEntityState(item);
_states.TryRemove(state.Key, out var trystate);
_fsql.ClearEntityPrimaryValueWithIdentityAndGuid(_entityType, item);
EnqueueToDbContext(DbContext.ExecCommandInfoType.Delete, state);
}
}
#endregion
EnqueueToDbContext(DbContext.ExecCommandInfoType.Delete, state);
}
}
#endregion
#region AddOrUpdate
/// <summary>
/// 添加或更新
/// </summary>
/// <param name="data"></param>
public void AddOrUpdate(TEntity data) {
if (data == null) throw new ArgumentNullException(nameof(data));
if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
#region AddOrUpdate
/// <summary>
/// 添加或更新
/// </summary>
/// <param name="data"></param>
public void AddOrUpdate(TEntity data)
{
if (data == null) throw new ArgumentNullException(nameof(data));
if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
var flagExists = ExistsInStates(data);
if (flagExists == false) {
var olddata = OrmSelect(data).First();
if (olddata == null) flagExists = false;
}
var flagExists = ExistsInStates(data);
if (flagExists == false)
{
var olddata = OrmSelect(data).First();
if (olddata == null) flagExists = false;
}
if (flagExists == true && CanUpdate(data, false)) {
DbContextExecCommand();
var affrows = _ctx._affrows;
UpdateRangePriv(new[] { data }, false);
DbContextExecCommand();
affrows = _ctx._affrows - affrows;
if (affrows > 0) return;
}
if (CanAdd(data, false)) {
_fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data);
AddPriv(data, false);
}
}
#endregion
}
if (flagExists == true && CanUpdate(data, false))
{
DbContextExecCommand();
var affrows = _ctx._affrows;
UpdateRangePriv(new[] { data }, false);
DbContextExecCommand();
affrows = _ctx._affrows - affrows;
if (affrows > 0) return;
}
if (CanAdd(data, false))
{
_fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data);
AddPriv(data, false);
}
}
#endregion
}
}

View File

@ -3,30 +3,35 @@
using Microsoft.Extensions.DependencyInjection;
using System;
namespace FreeSql {
public static class DbContextDependencyInjection {
namespace FreeSql
{
public static class DbContextDependencyInjection
{
public static IServiceCollection AddFreeDbContext<TDbContext>(this IServiceCollection services, Action<DbContextOptionsBuilder> options) where TDbContext : DbContext {
public static IServiceCollection AddFreeDbContext<TDbContext>(this IServiceCollection services, Action<DbContextOptionsBuilder> options) where TDbContext : DbContext
{
services.AddScoped<TDbContext>(sp => {
var ctx = Activator.CreateInstance<TDbContext>();
services.AddScoped<TDbContext>(sp =>
{
var ctx = Activator.CreateInstance<TDbContext>();
if (ctx._orm == null) {
var builder = new DbContextOptionsBuilder();
options(builder);
ctx._orm = builder._fsql;
if (ctx._orm == null)
{
var builder = new DbContextOptionsBuilder();
options(builder);
ctx._orm = builder._fsql;
if (ctx._orm == null)
throw new Exception("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql");
if (ctx._orm == null)
throw new Exception("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql");
ctx.InitPropSets();
}
ctx.InitPropSets();
}
return ctx;
});
return ctx;
});
return services;
}
}
return services;
}
}
}
#endif

View File

@ -2,37 +2,41 @@
using System;
using System.Collections.Concurrent;
public static class FreeSqlDbContextExtenssions {
public static class FreeSqlDbContextExtenssions
{
/// <summary>
/// 创建普通数据上下文档对象
/// </summary>
/// <param name="that"></param>
/// <returns></returns>
public static DbContext CreateDbContext(this IFreeSql that) {
return new FreeContext(that);
}
/// <summary>
/// 创建普通数据上下文档对象
/// </summary>
/// <param name="that"></param>
/// <returns></returns>
public static DbContext CreateDbContext(this IFreeSql that)
{
return new FreeContext(that);
}
/// <summary>
/// 不跟踪查询的实体数据(在不需要更新其数据时使用),可提长查询性能
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="select"></param>
/// <returns></returns>
public static ISelect<T> NoTracking<T>(this ISelect<T> select) where T : class {
return select.TrackToList(null);
}
/// <summary>
/// 不跟踪查询的实体数据(在不需要更新其数据时使用),可提长查询性能
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="select"></param>
/// <returns></returns>
public static ISelect<T> NoTracking<T>(this ISelect<T> select) where T : class
{
return select.TrackToList(null);
}
/// <summary>
/// 设置 DbContext 选项设置
/// </summary>
/// <param name="that"></param>
/// <param name="options"></param>
public static void SetDbContextOptions(this IFreeSql that, Action<DbContextOptions> options) {
if (options == null) return;
var cfg = _dicSetDbContextOptions.GetOrAdd(that, t => new DbContextOptions());
options(cfg);
_dicSetDbContextOptions.AddOrUpdate(that, cfg, (t, o) => cfg);
}
internal static ConcurrentDictionary<IFreeSql, DbContextOptions> _dicSetDbContextOptions = new ConcurrentDictionary<IFreeSql, DbContextOptions>();
/// <summary>
/// 设置 DbContext 选项设置
/// </summary>
/// <param name="that"></param>
/// <param name="options"></param>
public static void SetDbContextOptions(this IFreeSql that, Action<DbContextOptions> options)
{
if (options == null) return;
var cfg = _dicSetDbContextOptions.GetOrAdd(that, t => new DbContextOptions());
options(cfg);
_dicSetDbContextOptions.AddOrUpdate(that, cfg, (t, o) => cfg);
}
internal static ConcurrentDictionary<IFreeSql, DbContextOptions> _dicSetDbContextOptions = new ConcurrentDictionary<IFreeSql, DbContextOptions>();
}

View File

@ -3,60 +3,69 @@ using System.Collections.Concurrent;
using System.Reflection;
using System.Threading.Tasks;
namespace FreeSql {
internal class RepositoryDbContext : DbContext {
namespace FreeSql
{
internal class RepositoryDbContext : DbContext
{
protected IBaseRepository _repos;
public RepositoryDbContext(IFreeSql orm, IBaseRepository repos) : base() {
_orm = orm;
_repos = repos;
_isUseUnitOfWork = false;
_uowPriv = _repos.UnitOfWork;
}
protected IBaseRepository _repos;
public RepositoryDbContext(IFreeSql orm, IBaseRepository repos) : base()
{
_orm = orm;
_repos = repos;
_isUseUnitOfWork = false;
_uowPriv = _repos.UnitOfWork;
}
static ConcurrentDictionary<Type, FieldInfo> _dicGetRepositoryDbField = new ConcurrentDictionary<Type, FieldInfo>();
static FieldInfo GetRepositoryDbField(Type type) => _dicGetRepositoryDbField.GetOrAdd(type, tp => typeof(BaseRepository<,>).MakeGenericType(tp, typeof(int)).GetField("_dbPriv", BindingFlags.Instance | BindingFlags.NonPublic));
public override IDbSet Set(Type entityType) {
if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType];
static ConcurrentDictionary<Type, FieldInfo> _dicGetRepositoryDbField = new ConcurrentDictionary<Type, FieldInfo>();
static FieldInfo GetRepositoryDbField(Type type) => _dicGetRepositoryDbField.GetOrAdd(type, tp => typeof(BaseRepository<,>).MakeGenericType(tp, typeof(int)).GetField("_dbPriv", BindingFlags.Instance | BindingFlags.NonPublic));
public override IDbSet Set(Type entityType)
{
if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType];
var tb = _orm.CodeFirst.GetTableByEntity(entityType);
if (tb == null) return null;
var tb = _orm.CodeFirst.GetTableByEntity(entityType);
if (tb == null) return null;
object repos = _repos;
if (entityType != _repos.EntityType) {
repos = Activator.CreateInstance(typeof(DefaultRepository<,>).MakeGenericType(entityType, typeof(int)), _repos.Orm);
(repos as IBaseRepository).UnitOfWork = _repos.UnitOfWork;
GetRepositoryDbField(entityType).SetValue(repos, this);
object repos = _repos;
if (entityType != _repos.EntityType)
{
repos = Activator.CreateInstance(typeof(DefaultRepository<,>).MakeGenericType(entityType, typeof(int)), _repos.Orm);
(repos as IBaseRepository).UnitOfWork = _repos.UnitOfWork;
GetRepositoryDbField(entityType).SetValue(repos, this);
typeof(RepositoryDbContext).GetMethod("SetRepositoryDataFilter").MakeGenericMethod(_repos.EntityType)
.Invoke(null, new object[] { repos, _repos });
}
typeof(RepositoryDbContext).GetMethod("SetRepositoryDataFilter").MakeGenericMethod(_repos.EntityType)
.Invoke(null, new object[] { repos, _repos });
}
var sd = Activator.CreateInstance(typeof(RepositoryDbSet<>).MakeGenericType(entityType), repos) as IDbSet;
if (entityType != typeof(object)) _dicSet.Add(entityType, sd);
return sd;
}
var sd = Activator.CreateInstance(typeof(RepositoryDbSet<>).MakeGenericType(entityType), repos) as IDbSet;
if (entityType != typeof(object)) _dicSet.Add(entityType, sd);
return sd;
}
public static void SetRepositoryDataFilter<TEntity>(object repos, BaseRepository<TEntity> baseRepo) where TEntity : class {
var filter = baseRepo.DataFilter as DataFilter<TEntity>;
DataFilterUtil.SetRepositoryDataFilter(repos, fl => {
foreach (var f in filter._filters)
fl.Apply<TEntity>(f.Key, f.Value.Expression);
});
}
public static void SetRepositoryDataFilter<TEntity>(object repos, BaseRepository<TEntity> baseRepo) where TEntity : class
{
var filter = baseRepo.DataFilter as DataFilter<TEntity>;
DataFilterUtil.SetRepositoryDataFilter(repos, fl =>
{
foreach (var f in filter._filters)
fl.Apply<TEntity>(f.Key, f.Value.Expression);
});
}
public override int SaveChanges() {
ExecCommand();
var ret = _affrows;
_affrows = 0;
return ret;
}
async public override Task<int> SaveChangesAsync() {
await ExecCommandAsync();
var ret = _affrows;
_affrows = 0;
return ret;
}
}
public override int SaveChanges()
{
ExecCommand();
var ret = _affrows;
_affrows = 0;
return ret;
}
async public override Task<int> SaveChangesAsync()
{
await ExecCommandAsync();
var ret = _affrows;
_affrows = 0;
return ret;
}
}
}

View File

@ -3,58 +3,67 @@ using System;
using System.Collections.Generic;
using System.Linq;
namespace FreeSql {
internal class RepositoryDbSet<TEntity> : DbSet<TEntity> where TEntity : class {
namespace FreeSql
{
internal class RepositoryDbSet<TEntity> : DbSet<TEntity> where TEntity : class
{
protected BaseRepository<TEntity> _repos;
public RepositoryDbSet(BaseRepository<TEntity> repos) {
_ctx = repos._db;
_fsql = repos.Orm;
_uow = repos.UnitOfWork;
_repos = repos;
}
protected BaseRepository<TEntity> _repos;
public RepositoryDbSet(BaseRepository<TEntity> repos)
{
_ctx = repos._db;
_fsql = repos.Orm;
_uow = repos.UnitOfWork;
_repos = repos;
}
protected override ISelect<TEntity> OrmSelect(object dywhere) {
var select = base.OrmSelect(dywhere);
protected override ISelect<TEntity> OrmSelect(object dywhere)
{
var select = base.OrmSelect(dywhere);
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
foreach (var filter in filters) select.Where(filter.Value.Expression);
return select.AsTable(_repos.AsTableSelectInternal);
}
internal ISelect<TEntity> OrmSelectInternal(object dywhere) => OrmSelect(dywhere);
protected override IUpdate<TEntity> OrmUpdate(IEnumerable<TEntity> entitys) {
var update = base.OrmUpdate(entitys);
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
foreach (var filter in filters) {
if (entitys != null)
foreach (var entity in entitys)
if (filter.Value.ExpressionDelegate?.Invoke(entity) == false)
throw new Exception($"FreeSql.Repository Update 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},更新的数据不符合 {_fsql.GetEntityString(_entityType, entity)}");
update.Where(filter.Value.Expression);
}
return update.AsTable(_repos.AsTableInternal);
}
internal IUpdate<TEntity> OrmUpdateInternal(IEnumerable<TEntity> entitys) => OrmUpdate(entitys);
protected override IDelete<TEntity> OrmDelete(object dywhere) {
var delete = base.OrmDelete(dywhere);
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
foreach (var filter in filters) delete.Where(filter.Value.Expression);
return delete.AsTable(_repos.AsTableInternal);
}
internal IDelete<TEntity> OrmDeleteInternal(object dywhere) => OrmDelete(dywhere);
protected override IInsert<TEntity> OrmInsert(TEntity entity) => OrmInsert(new[] { entity });
protected override IInsert<TEntity> OrmInsert(IEnumerable<TEntity> entitys) {
var insert = base.OrmInsert(entitys);
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
foreach (var filter in filters) {
if (entitys != null)
foreach (var entity in entitys)
if (filter.Value.ExpressionDelegate?.Invoke(entity) == false)
throw new Exception($"FreeSql.Repository Insert 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},插入的数据不符合 {_fsql.GetEntityString(_entityType, entity)}");
}
return insert.AsTable(_repos.AsTableInternal);
}
internal IInsert<TEntity> OrmInsertInternal(TEntity entity) => OrmInsert(entity);
internal IInsert<TEntity> OrmInsertInternal(IEnumerable<TEntity> entitys) => OrmInsert(entitys);
}
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
foreach (var filter in filters) select.Where(filter.Value.Expression);
return select.AsTable(_repos.AsTableSelectInternal);
}
internal ISelect<TEntity> OrmSelectInternal(object dywhere) => OrmSelect(dywhere);
protected override IUpdate<TEntity> OrmUpdate(IEnumerable<TEntity> entitys)
{
var update = base.OrmUpdate(entitys);
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
foreach (var filter in filters)
{
if (entitys != null)
foreach (var entity in entitys)
if (filter.Value.ExpressionDelegate?.Invoke(entity) == false)
throw new Exception($"FreeSql.Repository Update 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},更新的数据不符合 {_fsql.GetEntityString(_entityType, entity)}");
update.Where(filter.Value.Expression);
}
return update.AsTable(_repos.AsTableInternal);
}
internal IUpdate<TEntity> OrmUpdateInternal(IEnumerable<TEntity> entitys) => OrmUpdate(entitys);
protected override IDelete<TEntity> OrmDelete(object dywhere)
{
var delete = base.OrmDelete(dywhere);
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
foreach (var filter in filters) delete.Where(filter.Value.Expression);
return delete.AsTable(_repos.AsTableInternal);
}
internal IDelete<TEntity> OrmDeleteInternal(object dywhere) => OrmDelete(dywhere);
protected override IInsert<TEntity> OrmInsert(TEntity entity) => OrmInsert(new[] { entity });
protected override IInsert<TEntity> OrmInsert(IEnumerable<TEntity> entitys)
{
var insert = base.OrmInsert(entitys);
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
foreach (var filter in filters)
{
if (entitys != null)
foreach (var entity in entitys)
if (filter.Value.ExpressionDelegate?.Invoke(entity) == false)
throw new Exception($"FreeSql.Repository Insert 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},插入的数据不符合 {_fsql.GetEntityString(_entityType, entity)}");
}
return insert.AsTable(_repos.AsTableInternal);
}
internal IInsert<TEntity> OrmInsertInternal(TEntity entity) => OrmInsert(entity);
internal IInsert<TEntity> OrmInsertInternal(IEnumerable<TEntity> entitys) => OrmInsert(entitys);
}
}

View File

@ -1,57 +1,64 @@
using System;
using System.Linq.Expressions;
namespace FreeSql {
namespace FreeSql
{
public interface IRepositoryUnitOfWork : IUnitOfWork {
/// <summary>
/// 在工作单元内创建默认仓库类,工作单元下的仓储操作具有事务特点
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <param name="filter">数据过滤 + 验证</param>
/// <returns></returns>
DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class;
public interface IRepositoryUnitOfWork : IUnitOfWork
{
/// <summary>
/// 在工作单元内创建默认仓库类,工作单元下的仓储操作具有事务特点
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <param name="filter">数据过滤 + 验证</param>
/// <returns></returns>
DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class;
/// <summary>
/// 在工作单元内创建联合主键的仓储类,工作单元下的仓储操作具有事务特点
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="filter">数据过滤 + 验证</param>
/// <returns></returns>
BaseRepository<TEntity> GetRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class;
/// <summary>
/// 在工作单元内创建联合主键的仓储类,工作单元下的仓储操作具有事务特点
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="filter">数据过滤 + 验证</param>
/// <returns></returns>
BaseRepository<TEntity> GetRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class;
/// <summary>
/// 在工作单元内创建仓库类,工作单元下的仓储操作具有事务特点
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="filter">数据过滤 + 验证</param>
/// <param name="asTable">分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository</param>
/// <returns></returns>
GuidRepository<TEntity> GetGuidRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null, Func<string, string> asTable = null) where TEntity : class;
}
/// <summary>
/// 在工作单元内创建仓库类,工作单元下的仓储操作具有事务特点
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="filter">数据过滤 + 验证</param>
/// <param name="asTable">分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository</param>
/// <returns></returns>
GuidRepository<TEntity> GetGuidRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null, Func<string, string> asTable = null) where TEntity : class;
}
class RepositoryUnitOfWork : UnitOfWork, IRepositoryUnitOfWork {
class RepositoryUnitOfWork : UnitOfWork, IRepositoryUnitOfWork
{
public RepositoryUnitOfWork(IFreeSql fsql) : base(fsql) {
}
public RepositoryUnitOfWork(IFreeSql fsql) : base(fsql)
{
}
public GuidRepository<TEntity> GetGuidRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null, Func<string, string> asTable = null) where TEntity : class {
var repos = new GuidRepository<TEntity>(_fsql, filter, asTable);
repos.UnitOfWork = this;
return repos;
}
public GuidRepository<TEntity> GetGuidRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null, Func<string, string> asTable = null) where TEntity : class
{
var repos = new GuidRepository<TEntity>(_fsql, filter, asTable);
repos.UnitOfWork = this;
return repos;
}
public DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class {
var repos = new DefaultRepository<TEntity, TKey>(_fsql, filter);
repos.UnitOfWork = this;
return repos;
}
public DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class
{
var repos = new DefaultRepository<TEntity, TKey>(_fsql, filter);
repos.UnitOfWork = this;
return repos;
}
public BaseRepository<TEntity> GetRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class {
var repos = new DefaultRepository<TEntity, int>(_fsql, filter);
repos.UnitOfWork = this;
return repos;
}
}
public BaseRepository<TEntity> GetRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class
{
var repos = new DefaultRepository<TEntity, int>(_fsql, filter);
repos.UnitOfWork = this;
return repos;
}
}
}

View File

@ -4,149 +4,178 @@ using System.Collections.Concurrent;
using System.Linq.Expressions;
using System.Linq;
namespace FreeSql {
public interface IDataFilter<TEntity> : IDisposable where TEntity : class {
namespace FreeSql
{
public interface IDataFilter<TEntity> : IDisposable where TEntity : class
{
IDataFilter<TEntity> Apply(string filterName, Expression<Func<TEntity, bool>> filterAndValidateExp);
IDataFilter<TEntity> Apply(string filterName, Expression<Func<TEntity, bool>> filterAndValidateExp);
/// <summary>
/// 开启过滤器,若使用 using 则使用完后,恢复为原有状态
/// </summary>
/// <param name="filterName">过滤器名称</param>
/// <returns></returns>
IDisposable Enable(params string[] filterName);
/// <summary>
/// 开启所有过滤器,若使用 using 则使用完后,恢复为原有状态
/// </summary>
/// <returns></returns>
IDisposable EnableAll();
/// <summary>
/// 开启过滤器,若使用 using 则使用完后,恢复为原有状态
/// </summary>
/// <param name="filterName">过滤器名称</param>
/// <returns></returns>
IDisposable Enable(params string[] filterName);
/// <summary>
/// 开启所有过滤器,若使用 using 则使用完后,恢复为原有状态
/// </summary>
/// <returns></returns>
IDisposable EnableAll();
/// <summary>
/// 禁用过滤器,若使用 using 则使用完后,恢复为原有状态
/// </summary>
/// <param name="filterName"></param>
/// <returns></returns>
IDisposable Disable(params string[] filterName);
/// <summary>
/// 禁用所有过滤器,若使用 using 则使用完后,恢复为原有状态
/// </summary>
/// <returns></returns>
IDisposable DisableAll();
/// <summary>
/// 禁用过滤器,若使用 using 则使用完后,恢复为原有状态
/// </summary>
/// <param name="filterName"></param>
/// <returns></returns>
IDisposable Disable(params string[] filterName);
/// <summary>
/// 禁用所有过滤器,若使用 using 则使用完后,恢复为原有状态
/// </summary>
/// <returns></returns>
IDisposable DisableAll();
bool IsEnabled(string filterName);
}
bool IsEnabled(string filterName);
}
internal class DataFilter<TEntity> : IDataFilter<TEntity> where TEntity : class {
internal class DataFilter<TEntity> : IDataFilter<TEntity> where TEntity : class
{
internal class FilterItem {
public Expression<Func<TEntity, bool>> Expression { get; set; }
Func<TEntity, bool> _expressionDelegate;
public Func<TEntity, bool> ExpressionDelegate => _expressionDelegate ?? (_expressionDelegate = Expression?.Compile());
public bool IsEnabled { get; set; }
}
internal class FilterItem
{
public Expression<Func<TEntity, bool>> Expression { get; set; }
Func<TEntity, bool> _expressionDelegate;
public Func<TEntity, bool> ExpressionDelegate => _expressionDelegate ?? (_expressionDelegate = Expression?.Compile());
public bool IsEnabled { get; set; }
}
internal ConcurrentDictionary<string, FilterItem> _filters = new ConcurrentDictionary<string, FilterItem>(StringComparer.CurrentCultureIgnoreCase);
public IDataFilter<TEntity> Apply(string filterName, Expression<Func<TEntity, bool>> filterAndValidateExp) {
internal ConcurrentDictionary<string, FilterItem> _filters = new ConcurrentDictionary<string, FilterItem>(StringComparer.CurrentCultureIgnoreCase);
public IDataFilter<TEntity> Apply(string filterName, Expression<Func<TEntity, bool>> filterAndValidateExp)
{
if (filterName == null)
throw new ArgumentNullException(nameof(filterName));
if (filterAndValidateExp == null) return this;
if (filterName == null)
throw new ArgumentNullException(nameof(filterName));
if (filterAndValidateExp == null) return this;
var filterItem = new FilterItem { Expression = filterAndValidateExp, IsEnabled = true };
_filters.AddOrUpdate(filterName, filterItem, (k, v) => filterItem);
return this;
}
var filterItem = new FilterItem { Expression = filterAndValidateExp, IsEnabled = true };
_filters.AddOrUpdate(filterName, filterItem, (k, v) => filterItem);
return this;
}
public IDisposable Disable(params string[] filterName) {
if (filterName == null || filterName.Any() == false) return new UsingAny(() => { });
public IDisposable Disable(params string[] filterName)
{
if (filterName == null || filterName.Any() == false) return new UsingAny(() => { });
List<string> restore = new List<string>();
foreach (var name in filterName) {
if (_filters.TryGetValue(name, out var tryfi)) {
if (tryfi.IsEnabled) {
restore.Add(name);
tryfi.IsEnabled = false;
}
}
}
return new UsingAny(() => this.Enable(restore.ToArray()));
}
public IDisposable DisableAll() {
List<string> restore = new List<string>();
foreach (var val in _filters) {
if (val.Value.IsEnabled) {
restore.Add(val.Key);
val.Value.IsEnabled = false;
}
}
return new UsingAny(() => this.Enable(restore.ToArray()));
}
class UsingAny : IDisposable {
Action _ondis;
public UsingAny(Action ondis) {
_ondis = ondis;
}
public void Dispose() {
_ondis?.Invoke();
}
}
List<string> restore = new List<string>();
foreach (var name in filterName)
{
if (_filters.TryGetValue(name, out var tryfi))
{
if (tryfi.IsEnabled)
{
restore.Add(name);
tryfi.IsEnabled = false;
}
}
}
return new UsingAny(() => this.Enable(restore.ToArray()));
}
public IDisposable DisableAll()
{
List<string> restore = new List<string>();
foreach (var val in _filters)
{
if (val.Value.IsEnabled)
{
restore.Add(val.Key);
val.Value.IsEnabled = false;
}
}
return new UsingAny(() => this.Enable(restore.ToArray()));
}
class UsingAny : IDisposable
{
Action _ondis;
public UsingAny(Action ondis)
{
_ondis = ondis;
}
public void Dispose()
{
_ondis?.Invoke();
}
}
public IDisposable Enable(params string[] filterName) {
if (filterName == null || filterName.Any() == false) return new UsingAny(() => { });
public IDisposable Enable(params string[] filterName)
{
if (filterName == null || filterName.Any() == false) return new UsingAny(() => { });
List<string> restore = new List<string>();
foreach (var name in filterName) {
if (_filters.TryGetValue(name, out var tryfi)) {
if (tryfi.IsEnabled == false) {
restore.Add(name);
tryfi.IsEnabled = true;
}
}
}
return new UsingAny(() => this.Disable(restore.ToArray()));
}
public IDisposable EnableAll() {
List<string> restore = new List<string>();
foreach (var val in _filters) {
if (val.Value.IsEnabled == false) {
restore.Add(val.Key);
val.Value.IsEnabled = true;
}
}
return new UsingAny(() => this.Disable(restore.ToArray()));
}
List<string> restore = new List<string>();
foreach (var name in filterName)
{
if (_filters.TryGetValue(name, out var tryfi))
{
if (tryfi.IsEnabled == false)
{
restore.Add(name);
tryfi.IsEnabled = true;
}
}
}
return new UsingAny(() => this.Disable(restore.ToArray()));
}
public IDisposable EnableAll()
{
List<string> restore = new List<string>();
foreach (var val in _filters)
{
if (val.Value.IsEnabled == false)
{
restore.Add(val.Key);
val.Value.IsEnabled = true;
}
}
return new UsingAny(() => this.Disable(restore.ToArray()));
}
public bool IsEnabled(string filterName) {
if (filterName == null) return false;
return _filters.TryGetValue(filterName, out var tryfi) ? tryfi.IsEnabled : false;
}
public bool IsEnabled(string filterName)
{
if (filterName == null) return false;
return _filters.TryGetValue(filterName, out var tryfi) ? tryfi.IsEnabled : false;
}
~DataFilter() {
this.Dispose();
}
public void Dispose() {
_filters.Clear();
}
}
~DataFilter()
{
this.Dispose();
}
public void Dispose()
{
_filters.Clear();
}
}
public class FluentDataFilter : IDisposable {
public class FluentDataFilter : IDisposable
{
internal List<(Type type, string name, LambdaExpression exp)> _filters = new List<(Type type, string name, LambdaExpression exp)>();
internal List<(Type type, string name, LambdaExpression exp)> _filters = new List<(Type type, string name, LambdaExpression exp)>();
public FluentDataFilter Apply<TEntity>(string filterName, Expression<Func<TEntity, bool>> filterAndValidateExp) where TEntity : class {
if (filterName == null)
throw new ArgumentNullException(nameof(filterName));
if (filterAndValidateExp == null) return this;
public FluentDataFilter Apply<TEntity>(string filterName, Expression<Func<TEntity, bool>> filterAndValidateExp) where TEntity : class
{
if (filterName == null)
throw new ArgumentNullException(nameof(filterName));
if (filterAndValidateExp == null) return this;
_filters.Add((typeof(TEntity), filterName, filterAndValidateExp));
return this;
}
_filters.Add((typeof(TEntity), filterName, filterAndValidateExp));
return this;
}
~FluentDataFilter() {
this.Dispose();
}
public void Dispose() {
_filters.Clear();
}
}
~FluentDataFilter()
{
this.Dispose();
}
public void Dispose()
{
_filters.Clear();
}
}
}

View File

@ -5,85 +5,100 @@ using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace FreeSql {
namespace FreeSql
{
internal class DataFilterUtil {
internal class DataFilterUtil
{
internal static Action<FluentDataFilter> _globalDataFilter;
internal static Action<FluentDataFilter> _globalDataFilter;
static ConcurrentDictionary<Type, Delegate> _dicSetRepositoryDataFilterApplyDataFilterFunc = new ConcurrentDictionary<Type, Delegate>();
static ConcurrentDictionary<Type, ConcurrentDictionary<string, bool>> _dicSetRepositoryDataFilterConvertFilterNotExists = new ConcurrentDictionary<Type, ConcurrentDictionary<string, bool>>();
internal static void SetRepositoryDataFilter(object repos, Action<FluentDataFilter> scopedDataFilter) {
if (scopedDataFilter != null) {
SetRepositoryDataFilter(repos, null);
}
if (scopedDataFilter == null) {
scopedDataFilter = _globalDataFilter;
}
if (scopedDataFilter == null) return;
using (var globalFilter = new FluentDataFilter()) {
scopedDataFilter(globalFilter);
static ConcurrentDictionary<Type, Delegate> _dicSetRepositoryDataFilterApplyDataFilterFunc = new ConcurrentDictionary<Type, Delegate>();
static ConcurrentDictionary<Type, ConcurrentDictionary<string, bool>> _dicSetRepositoryDataFilterConvertFilterNotExists = new ConcurrentDictionary<Type, ConcurrentDictionary<string, bool>>();
internal static void SetRepositoryDataFilter(object repos, Action<FluentDataFilter> scopedDataFilter)
{
if (scopedDataFilter != null)
{
SetRepositoryDataFilter(repos, null);
}
if (scopedDataFilter == null)
{
scopedDataFilter = _globalDataFilter;
}
if (scopedDataFilter == null) return;
using (var globalFilter = new FluentDataFilter())
{
scopedDataFilter(globalFilter);
var type = repos.GetType();
Type entityType = (repos as IBaseRepository).EntityType;
if (entityType == null) throw new Exception("FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository");
var type = repos.GetType();
Type entityType = (repos as IBaseRepository).EntityType;
if (entityType == null) throw new Exception("FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository");
var notExists = _dicSetRepositoryDataFilterConvertFilterNotExists.GetOrAdd(type, t => new ConcurrentDictionary<string, bool>());
var newFilter = new Dictionary<string, LambdaExpression>();
foreach (var gf in globalFilter._filters) {
if (notExists.ContainsKey(gf.name)) continue;
var notExists = _dicSetRepositoryDataFilterConvertFilterNotExists.GetOrAdd(type, t => new ConcurrentDictionary<string, bool>());
var newFilter = new Dictionary<string, LambdaExpression>();
foreach (var gf in globalFilter._filters)
{
if (notExists.ContainsKey(gf.name)) continue;
LambdaExpression newExp = null;
var filterParameter1 = Expression.Parameter(entityType, gf.exp.Parameters[0].Name);
try {
newExp = Expression.Lambda(
typeof(Func<,>).MakeGenericType(entityType, typeof(bool)),
new ReplaceVisitor().Modify(gf.exp.Body, filterParameter1),
filterParameter1
);
} catch {
notExists.TryAdd(gf.name, true); //防止第二次错误
continue;
}
newFilter.Add(gf.name, newExp);
}
if (newFilter.Any() == false) return;
LambdaExpression newExp = null;
var filterParameter1 = Expression.Parameter(entityType, gf.exp.Parameters[0].Name);
try
{
newExp = Expression.Lambda(
typeof(Func<,>).MakeGenericType(entityType, typeof(bool)),
new ReplaceVisitor().Modify(gf.exp.Body, filterParameter1),
filterParameter1
);
}
catch
{
notExists.TryAdd(gf.name, true); //防止第二次错误
continue;
}
newFilter.Add(gf.name, newExp);
}
if (newFilter.Any() == false) return;
var del = _dicSetRepositoryDataFilterApplyDataFilterFunc.GetOrAdd(type, t => {
var reposParameter = Expression.Parameter(type);
var nameParameter = Expression.Parameter(typeof(string));
var expressionParameter = Expression.Parameter(
typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(entityType, typeof(bool)))
);
return Expression.Lambda(
Expression.Block(
Expression.Call(reposParameter, type.GetMethod("ApplyDataFilter", BindingFlags.Instance | BindingFlags.NonPublic), nameParameter, expressionParameter)
),
new[] {
reposParameter, nameParameter, expressionParameter
}
).Compile();
});
foreach (var nf in newFilter) {
del.DynamicInvoke(repos, nf.Key, nf.Value);
}
newFilter.Clear();
}
}
}
var del = _dicSetRepositoryDataFilterApplyDataFilterFunc.GetOrAdd(type, t =>
{
var reposParameter = Expression.Parameter(type);
var nameParameter = Expression.Parameter(typeof(string));
var expressionParameter = Expression.Parameter(
typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(entityType, typeof(bool)))
);
return Expression.Lambda(
Expression.Block(
Expression.Call(reposParameter, type.GetMethod("ApplyDataFilter", BindingFlags.Instance | BindingFlags.NonPublic), nameParameter, expressionParameter)
),
new[] {
reposParameter, nameParameter, expressionParameter
}
).Compile();
});
foreach (var nf in newFilter)
{
del.DynamicInvoke(repos, nf.Key, nf.Value);
}
newFilter.Clear();
}
}
}
class ReplaceVisitor : ExpressionVisitor {
private ParameterExpression parameter;
class ReplaceVisitor : ExpressionVisitor
{
private ParameterExpression parameter;
public Expression Modify(Expression expression, ParameterExpression parameter) {
this.parameter = parameter;
return Visit(expression);
}
public Expression Modify(Expression expression, ParameterExpression parameter)
{
this.parameter = parameter;
return Visit(expression);
}
protected override Expression VisitMember(MemberExpression node) {
if (node.Expression?.NodeType == ExpressionType.Parameter)
return Expression.Property(parameter, node.Member.Name);
return base.VisitMember(node);
}
}
protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression?.NodeType == ExpressionType.Parameter)
return Expression.Property(parameter, node.Member.Name);
return base.VisitMember(node);
}
}
}

View File

@ -5,35 +5,41 @@ using System.Reflection;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
namespace FreeSql {
public static class FreeSqlRepositoryDependencyInjection {
namespace FreeSql
{
public static class FreeSqlRepositoryDependencyInjection
{
public static IServiceCollection AddFreeRepository(this IServiceCollection services, Action<FluentDataFilter> globalDataFilter = null, params Assembly[] assemblies) {
public static IServiceCollection AddFreeRepository(this IServiceCollection services, Action<FluentDataFilter> globalDataFilter = null, params Assembly[] assemblies)
{
DataFilterUtil._globalDataFilter = globalDataFilter;
DataFilterUtil._globalDataFilter = globalDataFilter;
services.AddScoped(typeof(IReadOnlyRepository<>), typeof(GuidRepository<>));
services.AddScoped(typeof(IBasicRepository<>), typeof(GuidRepository<>));
services.AddScoped(typeof(BaseRepository<>), typeof(GuidRepository<>));
services.AddScoped(typeof(GuidRepository<>));
services.AddScoped(typeof(IReadOnlyRepository<>), typeof(GuidRepository<>));
services.AddScoped(typeof(IBasicRepository<>), typeof(GuidRepository<>));
services.AddScoped(typeof(BaseRepository<>), typeof(GuidRepository<>));
services.AddScoped(typeof(GuidRepository<>));
services.AddScoped(typeof(IReadOnlyRepository<,>), typeof(DefaultRepository<,>));
services.AddScoped(typeof(IBasicRepository<,>), typeof(DefaultRepository<,>));
services.AddScoped(typeof(BaseRepository<,>), typeof(DefaultRepository<,>));
services.AddScoped(typeof(DefaultRepository<,>));
services.AddScoped(typeof(IReadOnlyRepository<,>), typeof(DefaultRepository<,>));
services.AddScoped(typeof(IBasicRepository<,>), typeof(DefaultRepository<,>));
services.AddScoped(typeof(BaseRepository<,>), typeof(DefaultRepository<,>));
services.AddScoped(typeof(DefaultRepository<,>));
if (assemblies?.Any() == true) {
foreach(var asse in assemblies) {
foreach (var repos in asse.GetTypes().Where(a => a.IsAbstract == false && typeof(IBaseRepository).IsAssignableFrom(a))) {
if (assemblies?.Any() == true)
{
foreach (var asse in assemblies)
{
foreach (var repos in asse.GetTypes().Where(a => a.IsAbstract == false && typeof(IBaseRepository).IsAssignableFrom(a)))
{
services.AddScoped(repos);
}
}
}
services.AddScoped(repos);
}
}
}
return services;
}
}
return services;
}
}
}
#endif

View File

@ -3,63 +3,69 @@ using System;
using System.Linq.Expressions;
using System.Linq;
public static class FreeSqlRepositoryExtenssions {
public static class FreeSqlRepositoryExtenssions
{
/// <summary>
/// 返回默认仓库类
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <param name="that"></param>
/// <param name="filter">数据过滤 + 验证</param>
/// <returns></returns>
public static DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(this IFreeSql that, Expression<Func<TEntity, bool>> filter = null) where TEntity : class {
return new DefaultRepository<TEntity, TKey>(that, filter);
}
/// <summary>
/// 返回默认仓库类
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <param name="that"></param>
/// <param name="filter">数据过滤 + 验证</param>
/// <returns></returns>
public static DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(this IFreeSql that, Expression<Func<TEntity, bool>> filter = null) where TEntity : class
{
return new DefaultRepository<TEntity, TKey>(that, filter);
}
/// <summary>
/// 返回默认仓库类,适用联合主键的仓储类
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="that"></param>
/// <param name="filter">数据过滤 + 验证</param>
/// <returns></returns>
public static BaseRepository<TEntity> GetRepository<TEntity>(this IFreeSql that, Expression<Func<TEntity, bool>> filter = null) where TEntity : class {
return new DefaultRepository<TEntity, int>(that, filter);
}
/// <summary>
/// 返回默认仓库类,适用联合主键的仓储类
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="that"></param>
/// <param name="filter">数据过滤 + 验证</param>
/// <returns></returns>
public static BaseRepository<TEntity> GetRepository<TEntity>(this IFreeSql that, Expression<Func<TEntity, bool>> filter = null) where TEntity : class
{
return new DefaultRepository<TEntity, int>(that, filter);
}
/// <summary>
/// 返回仓库类
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="that"></param>
/// <param name="filter">数据过滤 + 验证</param>
/// <param name="asTable">分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository</param>
/// <returns></returns>
public static GuidRepository<TEntity> GetGuidRepository<TEntity>(this IFreeSql that, Expression<Func<TEntity, bool>> filter = null, Func<string, string> asTable = null) where TEntity : class {
return new GuidRepository<TEntity>(that, filter, asTable);
}
/// <summary>
/// 返回仓库类
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="that"></param>
/// <param name="filter">数据过滤 + 验证</param>
/// <param name="asTable">分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository</param>
/// <returns></returns>
public static GuidRepository<TEntity> GetGuidRepository<TEntity>(this IFreeSql that, Expression<Func<TEntity, bool>> filter = null, Func<string, string> asTable = null) where TEntity : class
{
return new GuidRepository<TEntity>(that, filter, asTable);
}
/// <summary>
/// 合并两个仓储的设置(过滤+分表),以便查询
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <param name="that"></param>
/// <param name="repos"></param>
/// <returns></returns>
public static ISelect<TEntity> FromRepository<TEntity, T2>(this ISelect<TEntity> that, BaseRepository<T2> repos) where TEntity : class where T2 : class {
var filters = (repos.DataFilter as DataFilter<T2>)._filters.Where(a => a.Value.IsEnabled == true);
foreach (var filter in filters) that.Where<T2>(filter.Value.Expression);
return that.AsTable(repos.AsTableSelectInternal);
}
/// <summary>
/// 合并两个仓储的设置(过滤+分表),以便查询
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <param name="that"></param>
/// <param name="repos"></param>
/// <returns></returns>
public static ISelect<TEntity> FromRepository<TEntity, T2>(this ISelect<TEntity> that, BaseRepository<T2> repos) where TEntity : class where T2 : class
{
var filters = (repos.DataFilter as DataFilter<T2>)._filters.Where(a => a.Value.IsEnabled == true);
foreach (var filter in filters) that.Where<T2>(filter.Value.Expression);
return that.AsTable(repos.AsTableSelectInternal);
}
/// <summary>
/// 创建基于仓储功能的工作单元,务必使用 using 包含使用
/// </summary>
/// <param name="that"></param>
/// <returns></returns>
public static IRepositoryUnitOfWork CreateUnitOfWork(this IFreeSql that) {
return new RepositoryUnitOfWork(that);
}
/// <summary>
/// 创建基于仓储功能的工作单元,务必使用 using 包含使用
/// </summary>
/// <param name="that"></param>
/// <returns></returns>
public static IRepositoryUnitOfWork CreateUnitOfWork(this IFreeSql that)
{
return new RepositoryUnitOfWork(that);
}
}

View File

@ -4,157 +4,185 @@ using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace FreeSql {
public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity>
where TEntity : class {
namespace FreeSql
{
public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity>
where TEntity : class
{
internal RepositoryDbContext _dbPriv;
internal RepositoryDbContext _db => _dbPriv ?? (_dbPriv = new RepositoryDbContext(Orm, this));
internal RepositoryDbSet<TEntity> _dbsetPriv;
internal RepositoryDbSet<TEntity> _dbset => _dbsetPriv ?? (_dbsetPriv = _db.Set<TEntity>() as RepositoryDbSet<TEntity>);
public IDataFilter<TEntity> DataFilter { get; } = new DataFilter<TEntity>();
Func<string, string> _asTableVal;
protected Func<string, string> AsTable {
get => _asTableVal;
set {
_asTableVal = value;
AsTableSelect = value == null ? null : new Func<Type, string, string>((a, b) => a == EntityType ? value(b) : null);
}
}
internal Func<string, string> AsTableInternal => AsTable;
protected Func<Type, string, string> AsTableSelect { get; private set; }
internal Func<Type, string, string> AsTableSelectInternal => AsTableSelect;
internal RepositoryDbContext _dbPriv;
internal RepositoryDbContext _db => _dbPriv ?? (_dbPriv = new RepositoryDbContext(Orm, this));
internal RepositoryDbSet<TEntity> _dbsetPriv;
internal RepositoryDbSet<TEntity> _dbset => _dbsetPriv ?? (_dbsetPriv = _db.Set<TEntity>() as RepositoryDbSet<TEntity>);
public IDataFilter<TEntity> DataFilter { get; } = new DataFilter<TEntity>();
Func<string, string> _asTableVal;
protected Func<string, string> AsTable
{
get => _asTableVal;
set
{
_asTableVal = value;
AsTableSelect = value == null ? null : new Func<Type, string, string>((a, b) => a == EntityType ? value(b) : null);
}
}
internal Func<string, string> AsTableInternal => AsTable;
protected Func<Type, string, string> AsTableSelect { get; private set; }
internal Func<Type, string, string> AsTableSelectInternal => AsTableSelect;
protected void ApplyDataFilter(string name, Expression<Func<TEntity, bool>> exp) => DataFilter.Apply(name, exp);
protected void ApplyDataFilter(string name, Expression<Func<TEntity, bool>> exp) => DataFilter.Apply(name, exp);
protected BaseRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter, Func<string, string> asTable = null) {
Orm = fsql;
DataFilterUtil.SetRepositoryDataFilter(this, null);
DataFilter.Apply("", filter);
AsTable = asTable;
}
protected BaseRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter, Func<string, string> asTable = null)
{
Orm = fsql;
DataFilterUtil.SetRepositoryDataFilter(this, null);
DataFilter.Apply("", filter);
AsTable = asTable;
}
~BaseRepository() {
this.Dispose();
}
bool _isdisposed = false;
public void Dispose() {
if (_isdisposed) return;
try {
_dbsetPriv?.Dispose();
_dbPriv?.Dispose();
this.DataFilter.Dispose();
} finally {
_isdisposed = true;
GC.SuppressFinalize(this);
}
}
public Type EntityType => _dbsetPriv?.EntityType ?? typeof(TEntity);
public void AsType(Type entityType) => _dbset.AsType(entityType);
~BaseRepository()
{
this.Dispose();
}
bool _isdisposed = false;
public void Dispose()
{
if (_isdisposed) return;
try
{
_dbsetPriv?.Dispose();
_dbPriv?.Dispose();
this.DataFilter.Dispose();
}
finally
{
_isdisposed = true;
GC.SuppressFinalize(this);
}
}
public Type EntityType => _dbsetPriv?.EntityType ?? typeof(TEntity);
public void AsType(Type entityType) => _dbset.AsType(entityType);
public IFreeSql Orm { get; private set; }
public IUnitOfWork UnitOfWork { get; set; }
public IUpdate<TEntity> UpdateDiy => _dbset.OrmUpdateInternal(null);
public IFreeSql Orm { get; private set; }
public IUnitOfWork UnitOfWork { get; set; }
public IUpdate<TEntity> UpdateDiy => _dbset.OrmUpdateInternal(null);
public ISelect<TEntity> Select => _dbset.OrmSelectInternal(null);
public ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => _dbset.OrmSelectInternal(null).Where(exp);
public ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp) => _dbset.OrmSelectInternal(null).WhereIf(condition, exp);
public ISelect<TEntity> Select => _dbset.OrmSelectInternal(null);
public ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => _dbset.OrmSelectInternal(null).Where(exp);
public ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp) => _dbset.OrmSelectInternal(null).WhereIf(condition, exp);
public int Delete(Expression<Func<TEntity, bool>> predicate) => _dbset.OrmDeleteInternal(null).Where(predicate).ExecuteAffrows();
public Task<int> DeleteAsync(Expression<Func<TEntity, bool>> predicate) => _dbset.OrmDeleteInternal(null).Where(predicate).ExecuteAffrowsAsync();
public int Delete(Expression<Func<TEntity, bool>> predicate) => _dbset.OrmDeleteInternal(null).Where(predicate).ExecuteAffrows();
public Task<int> DeleteAsync(Expression<Func<TEntity, bool>> predicate) => _dbset.OrmDeleteInternal(null).Where(predicate).ExecuteAffrowsAsync();
public int Delete(TEntity entity) {
_dbset.Remove(entity);
return _db.SaveChanges();
}
public Task<int> DeleteAsync(TEntity entity) {
_dbset.Remove(entity);
return _db.SaveChangesAsync();
}
public int Delete(IEnumerable<TEntity> entitys) {
_dbset.RemoveRange(entitys);
return _db.SaveChanges();
}
public Task<int> DeleteAsync(IEnumerable<TEntity> entitys) {
_dbset.RemoveRange(entitys);
return _db.SaveChangesAsync();
}
public int Delete(TEntity entity)
{
_dbset.Remove(entity);
return _db.SaveChanges();
}
public Task<int> DeleteAsync(TEntity entity)
{
_dbset.Remove(entity);
return _db.SaveChangesAsync();
}
public int Delete(IEnumerable<TEntity> entitys)
{
_dbset.RemoveRange(entitys);
return _db.SaveChanges();
}
public Task<int> DeleteAsync(IEnumerable<TEntity> entitys)
{
_dbset.RemoveRange(entitys);
return _db.SaveChangesAsync();
}
public virtual TEntity Insert(TEntity entity) {
_dbset.Add(entity);
_db.SaveChanges();
return entity;
}
async public virtual Task<TEntity> InsertAsync(TEntity entity) {
await _dbset.AddAsync(entity);
_db.SaveChanges();
return entity;
}
public virtual List<TEntity> Insert(IEnumerable<TEntity> entitys) {
_dbset.AddRange(entitys);
_db.SaveChanges();
return entitys.ToList();
}
async public virtual Task<List<TEntity>> InsertAsync(IEnumerable<TEntity> entitys) {
await _dbset.AddRangeAsync(entitys);
await _db.SaveChangesAsync();
return entitys.ToList();
}
public virtual TEntity Insert(TEntity entity)
{
_dbset.Add(entity);
_db.SaveChanges();
return entity;
}
async public virtual Task<TEntity> InsertAsync(TEntity entity)
{
await _dbset.AddAsync(entity);
_db.SaveChanges();
return entity;
}
public virtual List<TEntity> Insert(IEnumerable<TEntity> entitys)
{
_dbset.AddRange(entitys);
_db.SaveChanges();
return entitys.ToList();
}
async public virtual Task<List<TEntity>> InsertAsync(IEnumerable<TEntity> entitys)
{
await _dbset.AddRangeAsync(entitys);
await _db.SaveChangesAsync();
return entitys.ToList();
}
public int Update(TEntity entity) {
_dbset.Update(entity);
return _db.SaveChanges();
}
public Task<int> UpdateAsync(TEntity entity) {
_dbset.Update(entity);
return _db.SaveChangesAsync();
}
public int Update(IEnumerable<TEntity> entitys) {
_dbset.UpdateRange(entitys);
return _db.SaveChanges();
}
public Task<int> UpdateAsync(IEnumerable<TEntity> entitys) {
_dbset.UpdateRange(entitys);
return _db.SaveChangesAsync();
}
public int Update(TEntity entity)
{
_dbset.Update(entity);
return _db.SaveChanges();
}
public Task<int> UpdateAsync(TEntity entity)
{
_dbset.Update(entity);
return _db.SaveChangesAsync();
}
public int Update(IEnumerable<TEntity> entitys)
{
_dbset.UpdateRange(entitys);
return _db.SaveChanges();
}
public Task<int> UpdateAsync(IEnumerable<TEntity> entitys)
{
_dbset.UpdateRange(entitys);
return _db.SaveChangesAsync();
}
public void Attach(TEntity data) => _db.Attach(data);
public void Attach(IEnumerable<TEntity> data) => _db.AttachRange(data);
public void FlushState() => _dbset.FlushState();
public void Attach(TEntity data) => _db.Attach(data);
public void Attach(IEnumerable<TEntity> data) => _db.AttachRange(data);
public void FlushState() => _dbset.FlushState();
public TEntity InsertOrUpdate(TEntity entity) {
_dbset.AddOrUpdate(entity);
_db.SaveChanges();
return entity;
}
async public Task<TEntity> InsertOrUpdateAsync(TEntity entity) {
await _dbset.AddOrUpdateAsync(entity);
_db.SaveChanges();
return entity;
}
}
public TEntity InsertOrUpdate(TEntity entity)
{
_dbset.AddOrUpdate(entity);
_db.SaveChanges();
return entity;
}
async public Task<TEntity> InsertOrUpdateAsync(TEntity entity)
{
await _dbset.AddOrUpdateAsync(entity);
_db.SaveChanges();
return entity;
}
}
public abstract class BaseRepository<TEntity, TKey> : BaseRepository<TEntity>, IBaseRepository<TEntity, TKey>
where TEntity : class {
public abstract class BaseRepository<TEntity, TKey> : BaseRepository<TEntity>, IBaseRepository<TEntity, TKey>
where TEntity : class
{
public BaseRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter, Func<string, string> asTable = null) : base(fsql, filter, asTable) {
}
public BaseRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter, Func<string, string> asTable = null) : base(fsql, filter, asTable)
{
}
public int Delete(TKey id) {
var stateKey = string.Concat(id);
_dbset._statesInternal.TryRemove(stateKey, out var trystate);
return _dbset.OrmDeleteInternal(id).ExecuteAffrows();
}
public Task<int> DeleteAsync(TKey id) {
var stateKey = string.Concat(id);
_dbset._statesInternal.TryRemove(stateKey, out var trystate);
return _dbset.OrmDeleteInternal(id).ExecuteAffrowsAsync();
}
public int Delete(TKey id)
{
var stateKey = string.Concat(id);
_dbset._statesInternal.TryRemove(stateKey, out var trystate);
return _dbset.OrmDeleteInternal(id).ExecuteAffrows();
}
public Task<int> DeleteAsync(TKey id)
{
var stateKey = string.Concat(id);
_dbset._statesInternal.TryRemove(stateKey, out var trystate);
return _dbset.OrmDeleteInternal(id).ExecuteAffrowsAsync();
}
public TEntity Find(TKey id) => _dbset.OrmSelectInternal(id).ToOne();
public Task<TEntity> FindAsync(TKey id) => _dbset.OrmSelectInternal(id).ToOneAsync();
public TEntity Find(TKey id) => _dbset.OrmSelectInternal(id).ToOne();
public Task<TEntity> FindAsync(TKey id) => _dbset.OrmSelectInternal(id).ToOneAsync();
public TEntity Get(TKey id) => Find(id);
public Task<TEntity> GetAsync(TKey id) => FindAsync(id);
}
public TEntity Get(TKey id) => Find(id);
public Task<TEntity> GetAsync(TKey id) => FindAsync(id);
}
}

View File

@ -1,16 +1,20 @@
using System;
using System.Linq.Expressions;
namespace FreeSql {
public class DefaultRepository<TEntity, TKey> :
BaseRepository<TEntity, TKey>
where TEntity : class {
namespace FreeSql
{
public class DefaultRepository<TEntity, TKey> :
BaseRepository<TEntity, TKey>
where TEntity : class
{
public DefaultRepository(IFreeSql fsql) : base(fsql, null, null) {
public DefaultRepository(IFreeSql fsql) : base(fsql, null, null)
{
}
}
public DefaultRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter) : base(fsql, filter, null) {
}
}
public DefaultRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter) : base(fsql, filter, null)
{
}
}
}

View File

@ -1,15 +1,19 @@
using System;
using System.Linq.Expressions;
namespace FreeSql {
public class GuidRepository<TEntity> :
BaseRepository<TEntity, Guid>
where TEntity : class {
namespace FreeSql
{
public class GuidRepository<TEntity> :
BaseRepository<TEntity, Guid>
where TEntity : class
{
public GuidRepository(IFreeSql fsql) : this(fsql, null, null) {
public GuidRepository(IFreeSql fsql) : this(fsql, null, null)
{
}
public GuidRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter, Func<string, string> asTable) : base(fsql, filter, asTable) {
}
}
}
public GuidRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter, Func<string, string> asTable) : base(fsql, filter, asTable)
{
}
}
}

View File

@ -2,29 +2,33 @@
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace FreeSql {
namespace FreeSql
{
public interface IBaseRepository : IDisposable {
Type EntityType { get; }
IUnitOfWork UnitOfWork { get; set; }
IFreeSql Orm { get; }
public interface IBaseRepository : IDisposable
{
Type EntityType { get; }
IUnitOfWork UnitOfWork { get; set; }
IFreeSql Orm { get; }
/// <summary>
/// 动态Type在使用 Repository&lt;object&gt; 后使用本方法,指定实体类型
/// </summary>
/// <param name="entityType"></param>
/// <returns></returns>
void AsType(Type entityType);
}
/// <summary>
/// 动态Type在使用 Repository&lt;object&gt; 后使用本方法,指定实体类型
/// </summary>
/// <param name="entityType"></param>
/// <returns></returns>
void AsType(Type entityType);
}
public interface IBaseRepository<TEntity> : IReadOnlyRepository<TEntity>, IBasicRepository<TEntity>
where TEntity : class {
int Delete(Expression<Func<TEntity, bool>> predicate);
public interface IBaseRepository<TEntity> : IReadOnlyRepository<TEntity>, IBasicRepository<TEntity>
where TEntity : class
{
int Delete(Expression<Func<TEntity, bool>> predicate);
Task<int> DeleteAsync(Expression<Func<TEntity, bool>> predicate);
}
Task<int> DeleteAsync(Expression<Func<TEntity, bool>> predicate);
}
public interface IBaseRepository<TEntity, TKey> : IBaseRepository<TEntity>, IReadOnlyRepository<TEntity, TKey>, IBasicRepository<TEntity, TKey>
where TEntity : class {
}
public interface IBaseRepository<TEntity, TKey> : IBaseRepository<TEntity>, IReadOnlyRepository<TEntity, TKey>, IBasicRepository<TEntity, TKey>
where TEntity : class
{
}
}

View File

@ -1,45 +1,48 @@
using System.Collections.Generic;
using System.Threading.Tasks;
namespace FreeSql {
public interface IBasicRepository<TEntity> : IReadOnlyRepository<TEntity>
where TEntity : class {
TEntity Insert(TEntity entity);
List<TEntity> Insert(IEnumerable<TEntity> entitys);
Task<TEntity> InsertAsync(TEntity entity);
Task<List<TEntity>> InsertAsync(IEnumerable<TEntity> entitys);
namespace FreeSql
{
public interface IBasicRepository<TEntity> : IReadOnlyRepository<TEntity>
where TEntity : class
{
TEntity Insert(TEntity entity);
List<TEntity> Insert(IEnumerable<TEntity> entitys);
Task<TEntity> InsertAsync(TEntity entity);
Task<List<TEntity>> InsertAsync(IEnumerable<TEntity> entitys);
/// <summary>
/// 清空状态数据
/// </summary>
void FlushState();
/// <summary>
/// 附加实体,可用于不查询就更新或删除
/// </summary>
/// <param name="entity"></param>
void Attach(TEntity entity);
void Attach(IEnumerable<TEntity> entity);
int Update(TEntity entity);
int Update(IEnumerable<TEntity> entitys);
Task<int> UpdateAsync(TEntity entity);
Task<int> UpdateAsync(IEnumerable<TEntity> entitys);
/// <summary>
/// 清空状态数据
/// </summary>
void FlushState();
/// <summary>
/// 附加实体,可用于不查询就更新或删除
/// </summary>
/// <param name="entity"></param>
void Attach(TEntity entity);
void Attach(IEnumerable<TEntity> entity);
int Update(TEntity entity);
int Update(IEnumerable<TEntity> entitys);
Task<int> UpdateAsync(TEntity entity);
Task<int> UpdateAsync(IEnumerable<TEntity> entitys);
TEntity InsertOrUpdate(TEntity entity);
Task<TEntity> InsertOrUpdateAsync(TEntity entity);
TEntity InsertOrUpdate(TEntity entity);
Task<TEntity> InsertOrUpdateAsync(TEntity entity);
IUpdate<TEntity> UpdateDiy { get; }
IUpdate<TEntity> UpdateDiy { get; }
int Delete(TEntity entity);
int Delete(IEnumerable<TEntity> entitys);
Task<int> DeleteAsync(TEntity entity);
Task<int> DeleteAsync(IEnumerable<TEntity> entitys);
}
int Delete(TEntity entity);
int Delete(IEnumerable<TEntity> entitys);
Task<int> DeleteAsync(TEntity entity);
Task<int> DeleteAsync(IEnumerable<TEntity> entitys);
}
public interface IBasicRepository<TEntity, TKey> : IBasicRepository<TEntity>, IReadOnlyRepository<TEntity, TKey>
where TEntity : class {
int Delete(TKey id);
public interface IBasicRepository<TEntity, TKey> : IBasicRepository<TEntity>, IReadOnlyRepository<TEntity, TKey>
where TEntity : class
{
int Delete(TKey id);
Task<int> DeleteAsync(TKey id);
}
Task<int> DeleteAsync(TKey id);
}
}

View File

@ -2,26 +2,29 @@
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace FreeSql {
public interface IReadOnlyRepository<TEntity> : IBaseRepository
where TEntity : class {
namespace FreeSql
{
public interface IReadOnlyRepository<TEntity> : IBaseRepository
where TEntity : class
{
IDataFilter<TEntity> DataFilter { get; }
IDataFilter<TEntity> DataFilter { get; }
ISelect<TEntity> Select { get; }
ISelect<TEntity> Select { get; }
ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp);
ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp);
}
ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp);
ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp);
}
public interface IReadOnlyRepository<TEntity, TKey> : IReadOnlyRepository<TEntity>
where TEntity : class {
TEntity Get(TKey id);
public interface IReadOnlyRepository<TEntity, TKey> : IReadOnlyRepository<TEntity>
where TEntity : class
{
TEntity Get(TKey id);
Task<TEntity> GetAsync(TKey id);
Task<TEntity> GetAsync(TKey id);
TEntity Find(TKey id);
TEntity Find(TKey id);
Task<TEntity> FindAsync(TKey id);
}
Task<TEntity> FindAsync(TKey id);
}
}

View File

@ -1,5 +1,7 @@

namespace FreeSql.Extensions.EntityUtil {
public static class TempExtensions {
}
namespace FreeSql.Extensions.EntityUtil
{
public static class TempExtensions
{
}
}

View File

@ -2,12 +2,14 @@
using System.Data;
using System.Data.Common;
namespace FreeSql {
public interface IUnitOfWork : IDisposable {
namespace FreeSql
{
public interface IUnitOfWork : IDisposable
{
DbTransaction GetOrBeginTransaction(bool isCreate = true);
DbTransaction GetOrBeginTransaction(bool isCreate = true);
IsolationLevel? IsolationLevel { get; set; }
IsolationLevel? IsolationLevel { get; set; }
/// <summary>
/// 是否启用工作单元
@ -16,7 +18,7 @@ namespace FreeSql {
void Commit();
void Rollback();
void Rollback();
/// <summary>
/// 禁用工作单元

View File

@ -3,22 +3,26 @@ using System;
using System.Data;
using System.Data.Common;
namespace FreeSql {
class UnitOfWork : IUnitOfWork {
namespace FreeSql
{
class UnitOfWork : IUnitOfWork
{
protected IFreeSql _fsql;
protected Object<DbConnection> _conn;
protected DbTransaction _tran;
protected IFreeSql _fsql;
protected Object<DbConnection> _conn;
protected DbTransaction _tran;
public UnitOfWork(IFreeSql fsql) {
_fsql = fsql;
}
public UnitOfWork(IFreeSql fsql)
{
_fsql = fsql;
}
void ReturnObject() {
_fsql.Ado.MasterPool.Return(_conn);
_tran = null;
_conn = null;
}
void ReturnObject()
{
_fsql.Ado.MasterPool.Return(_conn);
_tran = null;
_conn = null;
}
/// <summary>
@ -49,55 +53,74 @@ namespace FreeSql {
public IsolationLevel? IsolationLevel { get; set; }
public DbTransaction GetOrBeginTransaction(bool isCreate = true) {
public DbTransaction GetOrBeginTransaction(bool isCreate = true)
{
if (_tran != null) return _tran;
if (isCreate == false) return null;
if (_tran != null) return _tran;
if (isCreate == false) return null;
if (!Enable) return null;
if (_conn != null) _fsql.Ado.MasterPool.Return(_conn);
if (_conn != null) _fsql.Ado.MasterPool.Return(_conn);
_conn = _fsql.Ado.MasterPool.Get();
try {
_tran = IsolationLevel == null ?
_conn.Value.BeginTransaction() :
_conn.Value.BeginTransaction(IsolationLevel.Value);
} catch {
ReturnObject();
throw;
}
return _tran;
}
_conn = _fsql.Ado.MasterPool.Get();
try
{
_tran = IsolationLevel == null ?
_conn.Value.BeginTransaction() :
_conn.Value.BeginTransaction(IsolationLevel.Value);
}
catch
{
ReturnObject();
throw;
}
return _tran;
}
public void Commit() {
if (_tran != null) {
try {
_tran.Commit();
} finally {
ReturnObject();
}
}
}
public void Rollback() {
if (_tran != null) {
try {
_tran.Rollback();
} finally {
ReturnObject();
}
}
}
~UnitOfWork() {
this.Dispose();
}
bool _isdisposed = false;
public void Dispose() {
if (_isdisposed) return;
try {
this.Rollback();
} finally {
_isdisposed = true;
GC.SuppressFinalize(this);
}
}
}
public void Commit()
{
if (_tran != null)
{
try
{
_tran.Commit();
}
finally
{
ReturnObject();
}
}
}
public void Rollback()
{
if (_tran != null)
{
try
{
_tran.Rollback();
}
finally
{
ReturnObject();
}
}
}
~UnitOfWork()
{
this.Dispose();
}
bool _isdisposed = false;
public void Dispose()
{
if (_isdisposed) return;
try
{
this.Rollback();
}
finally
{
_isdisposed = true;
GC.SuppressFinalize(this);
}
}
}
}

View File

@ -1,118 +1,132 @@
using System;
using Xunit;
namespace FreeSql.Tests {
public class RepositoryTests {
namespace FreeSql.Tests
{
public class RepositoryTests
{
[Fact]
public void AddUpdate() {
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();
[Fact]
public void AddUpdate()
{
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();
var item = repos.Insert(new AddUpdateInfo());
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
var item = repos.Insert(new AddUpdateInfo());
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
item = repos.Insert(new AddUpdateInfo { Id = Guid.NewGuid() });
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
item = repos.Insert(new AddUpdateInfo { Id = Guid.NewGuid() });
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
item.Title = "xxx";
repos.Update(item);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
item.Title = "xxx";
repos.Update(item);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
Console.WriteLine(repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ToSql());
repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ExecuteAffrows();
Console.WriteLine(repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ToSql());
repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ExecuteAffrows();
item = repos.Find(item.Id);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
}
item = repos.Find(item.Id);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
}
[Fact]
public void UpdateAttach() {
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();
[Fact]
public void UpdateAttach()
{
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();
var item = new AddUpdateInfo { Id = Guid.NewGuid() };
repos.Attach(item);
var item = new AddUpdateInfo { Id = Guid.NewGuid() };
repos.Attach(item);
item.Title = "xxx";
repos.Update(item);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
item.Title = "xxx";
repos.Update(item);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
Console.WriteLine(repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ToSql());
repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ExecuteAffrows();
Console.WriteLine(repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ToSql());
repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ExecuteAffrows();
item = repos.Find(item.Id);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
}
item = repos.Find(item.Id);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
}
[Fact]
public void UpdateWhenNotExists() {
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();
[Fact]
public void UpdateWhenNotExists()
{
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();
var item = new AddUpdateInfo { Id = Guid.NewGuid() };
item.Title = "xxx";
Assert.Throws<Exception>(() => repos.Update(item));
}
var item = new AddUpdateInfo { Id = Guid.NewGuid() };
item.Title = "xxx";
Assert.Throws<Exception>(() => repos.Update(item));
}
[Fact]
public void Update() {
g.sqlite.Insert(new AddUpdateInfo()).ExecuteAffrows();
[Fact]
public void Update()
{
g.sqlite.Insert(new AddUpdateInfo()).ExecuteAffrows();
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();
var item = new AddUpdateInfo { Id = g.sqlite.Select<AddUpdateInfo>().First().Id };
var item = new AddUpdateInfo { Id = g.sqlite.Select<AddUpdateInfo>().First().Id };
item.Title = "xxx";
repos.Update(item);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
}
item.Title = "xxx";
repos.Update(item);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
}
public class AddUpdateInfo {
public class AddUpdateInfo
{
public Guid Id { get; set; }
public string Title { get; set; }
public Guid Id { get; set; }
public string Title { get; set; }
public int Clicks { get; set; } = 10;
}
public int Clicks { get; set; } = 10;
}
[Fact]
public void UnitOfWorkRepository() {
foreach (var fsql in new[] { g.sqlite, /*g.mysql, g.pgsql, g.oracle, g.sqlserver*/ }) {
[Fact]
public void UnitOfWorkRepository()
{
foreach (var fsql in new[] { g.sqlite, /*g.mysql, g.pgsql, g.oracle, g.sqlserver*/ })
{
fsql.CodeFirst.ConfigEntity<FlowModel>(f => {
f.Property(b => b.UserId).IsPrimary(true);
f.Property(b => b.Id).IsPrimary(true).IsIdentity(true);
f.Property(b => b.Name).IsNullable(false);
});
fsql.CodeFirst.ConfigEntity<FlowModel>(f =>
{
f.Property(b => b.UserId).IsPrimary(true);
f.Property(b => b.Id).IsPrimary(true).IsIdentity(true);
f.Property(b => b.Name).IsNullable(false);
});
FlowModel flow = new FlowModel() {
CreateTime = DateTime.Now,
Name = "aaa",
LastModifyTime = DateTime.Now,
UserId = 1,
};
var flowRepos = fsql.GetRepository<FlowModel>();
flowRepos.Insert(flow);
FlowModel flow = new FlowModel()
{
CreateTime = DateTime.Now,
Name = "aaa",
LastModifyTime = DateTime.Now,
UserId = 1,
};
var flowRepos = fsql.GetRepository<FlowModel>();
flowRepos.Insert(flow);
//ÊÂÎñÌí¼Ó
flow = new FlowModel() {
CreateTime = DateTime.Now,
Name = "aaa",
LastModifyTime = DateTime.Now,
UserId = 1,
};
using (var uow = fsql.CreateUnitOfWork()) {
flowRepos = uow.GetRepository<FlowModel>();
flowRepos.Insert(flow);
uow.Commit();
}
//ÊÂÎñÌí¼Ó
flow = new FlowModel()
{
CreateTime = DateTime.Now,
Name = "aaa",
LastModifyTime = DateTime.Now,
UserId = 1,
};
using (var uow = fsql.CreateUnitOfWork())
{
flowRepos = uow.GetRepository<FlowModel>();
flowRepos.Insert(flow);
uow.Commit();
}
}
}
}
[Fact]
public void UnitOfWorkRepositoryWithDisableBeforeInsert()
{
foreach (var fsql in new[] { g.sqlite, })
foreach (var fsql in new[] { g.sqlite, })
{
fsql.CodeFirst.ConfigEntity<FlowModel>(f => {
fsql.CodeFirst.ConfigEntity<FlowModel>(f =>
{
f.Property(b => b.UserId).IsPrimary(true);
f.Property(b => b.Id).IsPrimary(true).IsIdentity(true);
f.Property(b => b.Name).IsNullable(false);
@ -129,7 +143,7 @@ namespace FreeSql.Tests {
};
//清理掉数据库中已存在的数据,为了接下来的插入测试
flowRepos.Delete(a => a.UserId == 1 &&a.Name== "aaa");
flowRepos.Delete(a => a.UserId == 1 && a.Name == "aaa");
using (var uow = fsql.CreateUnitOfWork())
{
@ -140,7 +154,7 @@ namespace FreeSql.Tests {
//已关闭工作单元提不提交都没影响此处注释来确定工作单元开关是否生效关闭了不Commit也应该插入数据
//uow.Commit();
}
Assert.True(flowRepos.Select.Any(a => a.UserId == 1 && a.Name == "aaa"));
}
@ -149,7 +163,7 @@ namespace FreeSql.Tests {
[Fact]
public void UnitOfWorkRepositoryWithDisableAfterInsert()
{
foreach (var fsql in new[] {g.sqlite,})
foreach (var fsql in new[] { g.sqlite, })
{
fsql.CodeFirst.ConfigEntity<FlowModel>(f =>
{
@ -227,35 +241,37 @@ namespace FreeSql.Tests {
}
public partial class FlowModel {
public int UserId { get; set; }
public int Id { get; set; }
public int? ParentId { get; set; }
public string Name { get; set; }
public DateTime CreateTime { get; set; }
public DateTime LastModifyTime { get; set; }
public string Desc { get; set; }
}
public partial class FlowModel
{
public int UserId { get; set; }
public int Id { get; set; }
public int? ParentId { get; set; }
public string Name { get; set; }
public DateTime CreateTime { get; set; }
public DateTime LastModifyTime { get; set; }
public string Desc { get; set; }
}
[Fact]
public void AsType() {
g.sqlite.Insert(new AddUpdateInfo()).ExecuteAffrows();
[Fact]
public void AsType()
{
g.sqlite.Insert(new AddUpdateInfo()).ExecuteAffrows();
var repos = g.sqlite.GetGuidRepository<object>();
repos.AsType(typeof(AddUpdateInfo));
var repos = g.sqlite.GetGuidRepository<object>();
repos.AsType(typeof(AddUpdateInfo));
var item = new AddUpdateInfo();
repos.Insert(item);
repos.Update(item);
var item = new AddUpdateInfo();
repos.Insert(item);
repos.Update(item);
item.Clicks += 1;
repos.InsertOrUpdate(item);
item.Clicks += 1;
repos.InsertOrUpdate(item);
var item2 = repos.Find(item.Id) as AddUpdateInfo;
Assert.Equal(item.Clicks, item2.Clicks);
var item2 = repos.Find(item.Id) as AddUpdateInfo;
Assert.Equal(item.Clicks, item2.Clicks);
repos.DataFilter.Apply("xxx", a => (a as AddUpdateInfo).Clicks == 2);
Assert.Null(repos.Find(item.Id));
}
}
repos.DataFilter.Apply("xxx", a => (a as AddUpdateInfo).Clicks == 2);
Assert.Null(repos.Find(item.Id));
}
}
}

View File

@ -6,155 +6,175 @@ using Xunit;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace FreeSql.Tests {
public class UnitTest1 {
namespace FreeSql.Tests
{
public class UnitTest1
{
class testenumWhere {
public Guid id { get; set; }
public testenumWhereType type { get; set; }
}
public enum testenumWhereType { Menu, Class, Blaaa }
class testenumWhere
{
public Guid id { get; set; }
public testenumWhereType type { get; set; }
}
public enum testenumWhereType { Menu, Class, Blaaa }
[Fact]
public void Include_ManyToMany() {
[Fact]
public void Include_ManyToMany()
{
g.sqlite.CodeFirst.SyncStructure<Song_tag>();
g.sqlite.CodeFirst.SyncStructure<Tag>();
g.sqlite.CodeFirst.SyncStructure<Song>();
g.sqlite.CodeFirst.SyncStructure<Song_tag>();
g.sqlite.CodeFirst.SyncStructure<Tag>();
g.sqlite.CodeFirst.SyncStructure<Song>();
using (var ctx = g.sqlite.CreateDbContext()) {
using (var ctx = g.sqlite.CreateDbContext())
{
var songs = ctx.Set<Song>().Select
.IncludeMany(a => a.Tags)
.ToList();
var songs = ctx.Set<Song>().Select
.IncludeMany(a => a.Tags)
.ToList();
var tag1 = new Tag {
Ddd = DateTime.Now.Second,
Name = "test_manytoMany_01_中国"
};
var tag2 = new Tag {
Ddd = DateTime.Now.Second,
Name = "test_manytoMany_02_美国"
};
var tag3 = new Tag {
Ddd = DateTime.Now.Second,
Name = "test_manytoMany_03_日本"
};
ctx.AddRange(new[] { tag1, tag2, tag3 });
var tag1 = new Tag
{
Ddd = DateTime.Now.Second,
Name = "test_manytoMany_01_中国"
};
var tag2 = new Tag
{
Ddd = DateTime.Now.Second,
Name = "test_manytoMany_02_美国"
};
var tag3 = new Tag
{
Ddd = DateTime.Now.Second,
Name = "test_manytoMany_03_日本"
};
ctx.AddRange(new[] { tag1, tag2, tag3 });
var song1 = new Song {
Create_time = DateTime.Now,
Title = "test_manytoMany_01_我是中国人.mp3",
Url = "http://ww.baidu.com/"
};
var song2 = new Song {
Create_time = DateTime.Now,
Title = "test_manytoMany_02_爱你一万年.mp3",
Url = "http://ww.163.com/"
};
var song3 = new Song {
Create_time = DateTime.Now,
Title = "test_manytoMany_03_千年等一回.mp3",
Url = "http://ww.sina.com/"
};
ctx.AddRange(new[] { song1, song2, song3 });
var song1 = new Song
{
Create_time = DateTime.Now,
Title = "test_manytoMany_01_我是中国人.mp3",
Url = "http://ww.baidu.com/"
};
var song2 = new Song
{
Create_time = DateTime.Now,
Title = "test_manytoMany_02_爱你一万年.mp3",
Url = "http://ww.163.com/"
};
var song3 = new Song
{
Create_time = DateTime.Now,
Title = "test_manytoMany_03_千年等一回.mp3",
Url = "http://ww.sina.com/"
};
ctx.AddRange(new[] { song1, song2, song3 });
ctx.AddRange(
new[] {
new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id },
new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id },
new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id },
new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id },
new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id },
new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id },
}
);
ctx.SaveChanges();
}
}
ctx.AddRange(
new[] {
new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id },
new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id },
new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id },
new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id },
new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id },
new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id },
}
);
ctx.SaveChanges();
}
}
[Fact]
public void Add() {
[Fact]
public void Add()
{
g.sqlite.SetDbContextOptions(opt => {
//opt.EnableAddOrUpdateNavigateList = false;
});
g.sqlite.SetDbContextOptions(opt =>
{
//opt.EnableAddOrUpdateNavigateList = false;
});
g.mysql.Insert<testenumWhere>().AppendData(new testenumWhere { type = testenumWhereType.Blaaa }).ExecuteAffrows();
g.mysql.Insert<testenumWhere>().AppendData(new testenumWhere { type = testenumWhereType.Blaaa }).ExecuteAffrows();
var sql = g.mysql.Select<testenumWhere>().Where(a => a.type == testenumWhereType.Blaaa).ToSql();
var tolist = g.mysql.Select<testenumWhere>().Where(a => a.type == testenumWhereType.Blaaa).ToList();
var sql = g.mysql.Select<testenumWhere>().Where(a => a.type == testenumWhereType.Blaaa).ToSql();
var tolist = g.mysql.Select<testenumWhere>().Where(a => a.type == testenumWhereType.Blaaa).ToList();
//支持 1对多 联级保存
//支持 1对多 联级保存
using (var ctx = new FreeContext(g.sqlite)) {
using (var ctx = new FreeContext(g.sqlite))
{
var tags = ctx.Set<Tag>().Select.IncludeMany(a => a.Tags).ToList();
var tags = ctx.Set<Tag>().Select.IncludeMany(a => a.Tags).ToList();
var tag = new Tag {
Name = "testaddsublist",
Tags = new[] {
new Tag { Name = "sub1" },
new Tag { Name = "sub2" },
new Tag {
Name = "sub3",
Tags = new[] {
new Tag { Name = "sub3_01" }
}
}
}
};
ctx.Add(tag);
ctx.SaveChanges();
}
}
var tag = new Tag
{
Name = "testaddsublist",
Tags = new[] {
new Tag { Name = "sub1" },
new Tag { Name = "sub2" },
new Tag {
Name = "sub3",
Tags = new[] {
new Tag { Name = "sub3_01" }
}
}
}
};
ctx.Add(tag);
ctx.SaveChanges();
}
}
[Fact]
public void Update() {
//查询 1对多再联级保存
[Fact]
public void Update()
{
//查询 1对多再联级保存
using (var ctx = new FreeContext(g.sqlite)) {
using (var ctx = new FreeContext(g.sqlite))
{
var tag = ctx.Set<Tag>().Select.First();
tag.Tags.Add(new Tag { Name = "sub3" });
ctx.Update(tag);
ctx.SaveChanges();
}
}
var tag = ctx.Set<Tag>().Select.First();
tag.Tags.Add(new Tag { Name = "sub3" });
ctx.Update(tag);
ctx.SaveChanges();
}
}
public class Song {
[Column(IsIdentity = true)]
public int Id { get; set; }
public DateTime? Create_time { get; set; }
public bool? Is_deleted { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public class Song
{
[Column(IsIdentity = true)]
public int Id { get; set; }
public DateTime? Create_time { get; set; }
public bool? Is_deleted { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
[Column(IsVersion = true)]
public long versionRow { get; set; }
}
public class Song_tag {
public int Song_id { get; set; }
public virtual Song Song { get; set; }
[Column(IsVersion = true)]
public long versionRow { get; set; }
}
public class Song_tag
{
public int Song_id { get; set; }
public virtual Song Song { get; set; }
public int Tag_id { get; set; }
public virtual Tag Tag { get; set; }
}
public int Tag_id { get; set; }
public virtual Tag Tag { get; set; }
}
public class Tag {
[Column(IsIdentity = true)]
public int Id { get; set; }
public int? Parent_id { get; set; }
public virtual Tag Parent { get; set; }
public class Tag
{
[Column(IsIdentity = true)]
public int Id { get; set; }
public int? Parent_id { get; set; }
public virtual Tag Parent { get; set; }
public decimal? Ddd { get; set; }
public string Name { get; set; }
public decimal? Ddd { get; set; }
public string Name { get; set; }
public virtual ICollection<Song> Songs { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
}
public virtual ICollection<Song> Songs { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
}
}

View File

@ -4,83 +4,94 @@ using System.Diagnostics;
using System.Text;
public class g {
public class g
{
static Lazy<IFreeSql> sqlserverLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseMonitorCommand(
cmd => {
Trace.WriteLine(cmd.CommandText);
}, //监听SQL命令对象在执行前
(cmd, traceLog) => {
Console.WriteLine(traceLog);
}) //监听SQL命令对象在执行后
.UseLazyLoading(true)
.UseNoneCommandParameter(true)
.Build());
public static IFreeSql sqlserver => sqlserverLazy.Value;
static Lazy<IFreeSql> sqlserverLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseMonitorCommand(
cmd =>
{
Trace.WriteLine(cmd.CommandText);
}, //监听SQL命令对象在执行前
(cmd, traceLog) =>
{
Console.WriteLine(traceLog);
}) //监听SQL命令对象在执行后
.UseLazyLoading(true)
.UseNoneCommandParameter(true)
.Build());
public static IFreeSql sqlserver => sqlserverLazy.Value;
static Lazy<IFreeSql> mysqlLazy = new Lazy<IFreeSql>(() => 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")
.UseAutoSyncStructure(true)
.UseMonitorCommand(
cmd => {
Trace.WriteLine(cmd.CommandText);
}, //监听SQL命令对象在执行前
(cmd, traceLog) => {
Console.WriteLine(traceLog);
}) //监听SQL命令对象在执行后
.UseLazyLoading(true)
.UseNoneCommandParameter(true)
.Build());
public static IFreeSql mysql => mysqlLazy.Value;
static Lazy<IFreeSql> mysqlLazy = new Lazy<IFreeSql>(() => 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")
.UseAutoSyncStructure(true)
.UseMonitorCommand(
cmd =>
{
Trace.WriteLine(cmd.CommandText);
}, //监听SQL命令对象在执行前
(cmd, traceLog) =>
{
Console.WriteLine(traceLog);
}) //监听SQL命令对象在执行后
.UseLazyLoading(true)
.UseNoneCommandParameter(true)
.Build());
public static IFreeSql mysql => mysqlLazy.Value;
static Lazy<IFreeSql> pgsqlLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=10")
.UseAutoSyncStructure(true)
.UseSyncStructureToLower(true)
.UseLazyLoading(true)
.UseMonitorCommand(
cmd => {
Trace.WriteLine(cmd.CommandText);
}, //监听SQL命令对象在执行前
(cmd, traceLog) => {
Console.WriteLine(traceLog);
}) //监听SQL命令对象在执行后
.UseNoneCommandParameter(true)
.Build());
public static IFreeSql pgsql => pgsqlLazy.Value;
static Lazy<IFreeSql> pgsqlLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=10")
.UseAutoSyncStructure(true)
.UseSyncStructureToLower(true)
.UseLazyLoading(true)
.UseMonitorCommand(
cmd =>
{
Trace.WriteLine(cmd.CommandText);
}, //监听SQL命令对象在执行前
(cmd, traceLog) =>
{
Console.WriteLine(traceLog);
}) //监听SQL命令对象在执行后
.UseNoneCommandParameter(true)
.Build());
public static IFreeSql pgsql => pgsqlLazy.Value;
static Lazy<IFreeSql> oracleLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
.UseSyncStructureToUpper(true)
.UseNoneCommandParameter(true)
static Lazy<IFreeSql> oracleLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
.UseSyncStructureToUpper(true)
.UseNoneCommandParameter(true)
.UseMonitorCommand(
cmd => {
Trace.WriteLine(cmd.CommandText);
}, //监听SQL命令对象在执行前
(cmd, traceLog) => {
Console.WriteLine(traceLog);
}) //监听SQL命令对象在执行后
.Build());
public static IFreeSql oracle => oracleLazy.Value;
.UseMonitorCommand(
cmd =>
{
Trace.WriteLine(cmd.CommandText);
}, //监听SQL命令对象在执行前
(cmd, traceLog) =>
{
Console.WriteLine(traceLog);
}) //监听SQL命令对象在执行后
.Build());
public static IFreeSql oracle => oracleLazy.Value;
static Lazy<IFreeSql> sqliteLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|/document22.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
.UseMonitorCommand(
cmd => {
Trace.WriteLine(cmd.CommandText);
}, //监听SQL命令对象在执行前
(cmd, traceLog) => {
Console.WriteLine(traceLog);
}) //监听SQL命令对象在执行后
.UseNoneCommandParameter(true)
.Build());
public static IFreeSql sqlite => sqliteLazy.Value;
static Lazy<IFreeSql> sqliteLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|/document22.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
.UseMonitorCommand(
cmd =>
{
Trace.WriteLine(cmd.CommandText);
}, //监听SQL命令对象在执行前
(cmd, traceLog) =>
{
Console.WriteLine(traceLog);
}) //监听SQL命令对象在执行后
.UseNoneCommandParameter(true)
.Build());
public static IFreeSql sqlite => sqliteLazy.Value;
}

View File

@ -9,191 +9,216 @@ using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
namespace FreeSql.Tests.PerformanceTest {
public class MySqlAdoTest {
namespace FreeSql.Tests.PerformanceTest
{
public class MySqlAdoTest
{
[Fact]
public void Query() {
var sb = new StringBuilder();
var time = new Stopwatch();
[Fact]
public void Query()
{
var sb = new StringBuilder();
var time = new Stopwatch();
time.Restart();
List<xxx> dplist1 = null;
using (var conn = g.mysql.Ado.MasterPool.Get()) {
dplist1 = Dapper.SqlMapper.Query<xxx>(conn.Value, "select * from song").ToList();
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper");
time.Restart();
List<xxx> dplist1 = null;
using (var conn = g.mysql.Ado.MasterPool.Get())
{
dplist1 = Dapper.SqlMapper.Query<xxx>(conn.Value, "select * from song").ToList();
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper");
time.Restart();
List<(int, string, string)> dplist2 = null;
using (var conn = g.mysql.Ado.MasterPool.Get()) {
dplist2 = Dapper.SqlMapper.Query<(int, string, string)>(conn.Value, "select * from song").ToList();
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {dplist2.Count}; ORM: Dapper");
time.Restart();
List<(int, string, string)> dplist2 = null;
using (var conn = g.mysql.Ado.MasterPool.Get())
{
dplist2 = Dapper.SqlMapper.Query<(int, string, string)>(conn.Value, "select * from song").ToList();
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {dplist2.Count}; ORM: Dapper");
time.Restart();
List<dynamic> dplist3 = null;
using (var conn = g.mysql.Ado.MasterPool.Get()) {
dplist3 = Dapper.SqlMapper.Query<dynamic>(conn.Value, "select * from song").ToList();
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {dplist3.Count}; ORM: Dapper");
time.Restart();
List<dynamic> dplist3 = null;
using (var conn = g.mysql.Ado.MasterPool.Get())
{
dplist3 = Dapper.SqlMapper.Query<dynamic>(conn.Value, "select * from song").ToList();
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {dplist3.Count}; ORM: Dapper");
var t31 = g.mysql.Ado.Query<xxx>("select * from song limit 1");
var t31 = g.mysql.Ado.Query<xxx>("select * from song limit 1");
time.Restart();
var t3 = g.mysql.Ado.Query<xxx>("select * from song");
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {t3.Count}; ORM: FreeSql*");
time.Restart();
var t3 = g.mysql.Ado.Query<xxx>("select * from song");
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {t3.Count}; ORM: FreeSql*");
time.Restart();
var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song");
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {t4.Count}; ORM: FreeSql*");
time.Restart();
var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song");
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {t4.Count}; ORM: FreeSql*");
time.Restart();
var t41 = g.mysql.Select<xxx>().ToList<(int, string, string)>("id,title,url");
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query ToList<Tuple> Counts: {t41.Count}; ORM: FreeSql*");
time.Restart();
var t41 = g.mysql.Select<xxx>().ToList<(int, string, string)>("id,title,url");
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query ToList<Tuple> Counts: {t41.Count}; ORM: FreeSql*");
time.Restart();
var t5 = g.mysql.Ado.Query<dynamic>("select * from song");
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {t3.Count}; ORM: FreeSql*");
time.Restart();
var t5 = g.mysql.Ado.Query<dynamic>("select * from song");
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {t3.Count}; ORM: FreeSql*");
}
}
[Fact]
public void QueryLimit10() {
var sb = new StringBuilder();
var time = new Stopwatch();
[Fact]
public void QueryLimit10()
{
var sb = new StringBuilder();
var time = new Stopwatch();
time.Restart();
List<xxx> dplist1 = new List<xxx>();
for (var a = 0; a < 10000; a++) {
using (var conn = g.mysql.Ado.MasterPool.Get()) {
dplist1.AddRange(Dapper.SqlMapper.Query<xxx>(conn.Value, "select * from song limit 10").ToList());
}
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper");
time.Restart();
List<xxx> dplist1 = new List<xxx>();
for (var a = 0; a < 10000; a++)
{
using (var conn = g.mysql.Ado.MasterPool.Get())
{
dplist1.AddRange(Dapper.SqlMapper.Query<xxx>(conn.Value, "select * from song limit 10").ToList());
}
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper");
time.Restart();
List<(int, string, string)> dplist2 = new List<(int, string, string)>();
for (var a = 0; a < 10000; a++) {
using (var conn = g.mysql.Ado.MasterPool.Get()) {
dplist2.AddRange(Dapper.SqlMapper.Query<(int, string, string)>(conn.Value, "select * from song limit 10").ToList());
}
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {dplist2.Count}; ORM: Dapper");
time.Restart();
List<(int, string, string)> dplist2 = new List<(int, string, string)>();
for (var a = 0; a < 10000; a++)
{
using (var conn = g.mysql.Ado.MasterPool.Get())
{
dplist2.AddRange(Dapper.SqlMapper.Query<(int, string, string)>(conn.Value, "select * from song limit 10").ToList());
}
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {dplist2.Count}; ORM: Dapper");
time.Restart();
List<dynamic> dplist3 = new List<dynamic>();
for (var a = 0; a < 10000; a++) {
using (var conn = g.mysql.Ado.MasterPool.Get()) {
dplist3.AddRange(Dapper.SqlMapper.Query<dynamic>(conn.Value, "select * from song limit 10").ToList());
}
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {dplist3.Count}; ORM: Dapper");
time.Restart();
List<dynamic> dplist3 = new List<dynamic>();
for (var a = 0; a < 10000; a++)
{
using (var conn = g.mysql.Ado.MasterPool.Get())
{
dplist3.AddRange(Dapper.SqlMapper.Query<dynamic>(conn.Value, "select * from song limit 10").ToList());
}
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {dplist3.Count}; ORM: Dapper");
time.Restart();
List<xxx> t3 = new List<xxx>();
for (var a = 0; a < 10000; a++) {
t3.AddRange(g.mysql.Ado.Query<xxx>("select * from song limit 10"));
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {t3.Count}; ORM: FreeSql*");
time.Restart();
List<xxx> t3 = new List<xxx>();
for (var a = 0; a < 10000; a++)
{
t3.AddRange(g.mysql.Ado.Query<xxx>("select * from song limit 10"));
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {t3.Count}; ORM: FreeSql*");
time.Restart();
List<(int, string, string)> t4 = new List<(int, string, string)>();
for (var a = 0; a < 10000; a++) {
t4.AddRange(g.mysql.Ado.Query<(int, string, string)>("select * from song limit 10"));
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {t4.Count}; ORM: FreeSql*");
time.Restart();
List<(int, string, string)> t4 = new List<(int, string, string)>();
for (var a = 0; a < 10000; a++)
{
t4.AddRange(g.mysql.Ado.Query<(int, string, string)>("select * from song limit 10"));
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {t4.Count}; ORM: FreeSql*");
time.Restart();
List<dynamic> t5 = new List<dynamic>();
for (var a = 0; a < 10000; a++) {
t5.AddRange(g.mysql.Ado.Query<dynamic>("select * from song limit 10"));
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {t3.Count}; ORM: FreeSql*");
time.Restart();
List<dynamic> t5 = new List<dynamic>();
for (var a = 0; a < 10000; a++)
{
t5.AddRange(g.mysql.Ado.Query<dynamic>("select * from song limit 10"));
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {t3.Count}; ORM: FreeSql*");
}
}
[Fact]
public void ToList() {
var sb = new StringBuilder();
var time = new Stopwatch();
[Fact]
public void ToList()
{
var sb = new StringBuilder();
var time = new Stopwatch();
//var t31 = g.mysql.Select<xxx>().ToList();
//var t31 = g.mysql.Select<xxx>().ToList();
time.Restart();
var t3 = g.mysql.Select<xxx>().ToList();
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; ToList Entity Counts: {t3.Count}; ORM: FreeSql*");
time.Restart();
var t3 = g.mysql.Select<xxx>().ToList();
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; ToList Entity Counts: {t3.Count}; ORM: FreeSql*");
time.Restart();
List<xxx> dplist1 = null;
using (var conn = g.mysql.Ado.MasterPool.Get()) {
dplist1 = Dapper.SqlMapper.Query<xxx>(conn.Value, "select * from song").ToList();
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper");
}
time.Restart();
List<xxx> dplist1 = null;
using (var conn = g.mysql.Ado.MasterPool.Get())
{
dplist1 = Dapper.SqlMapper.Query<xxx>(conn.Value, "select * from song").ToList();
}
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper");
}
[Fact]
public void ToListLimit10() {
var sb = new StringBuilder();
var time = new Stopwatch();
[Fact]
public void ToListLimit10()
{
var sb = new StringBuilder();
var time = new Stopwatch();
time.Restart();
var t3Count = 0;
var p3 = Parallel.For(1, 50, b => {
List<xxx> t3 = new List<xxx>();
for (var a = 0; a < 1000; a++) {
t3.AddRange(g.mysql.Select<xxx>().Limit(50).ToList());
}
Interlocked.Add(ref t3Count, t3.Count);
});
while (p3.IsCompleted == false) ;
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; ToList Entity Counts: {t3Count}; ORM: FreeSql*");
time.Restart();
var t3Count = 0;
var p3 = Parallel.For(1, 50, b =>
{
List<xxx> t3 = new List<xxx>();
for (var a = 0; a < 1000; a++)
{
t3.AddRange(g.mysql.Select<xxx>().Limit(50).ToList());
}
Interlocked.Add(ref t3Count, t3.Count);
});
while (p3.IsCompleted == false) ;
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; ToList Entity Counts: {t3Count}; ORM: FreeSql*");
time.Restart();
var dplist1Count = 0;
var p1 = Parallel.For(1, 50, b => {
List<xxx> dplist1 = new List<xxx>();
for (var a = 0; a < 1000; a++) {
using (var conn = g.mysql.Ado.MasterPool.Get()) {
dplist1.AddRange(Dapper.SqlMapper.Query<xxx>(conn.Value, "select * from song limit 50").ToList());
}
}
Interlocked.Add(ref dplist1Count, dplist1.Count);
});
while (p1.IsCompleted == false) ;
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1Count}; ORM: Dapper");
}
time.Restart();
var dplist1Count = 0;
var p1 = Parallel.For(1, 50, b =>
{
List<xxx> dplist1 = new List<xxx>();
for (var a = 0; a < 1000; a++)
{
using (var conn = g.mysql.Ado.MasterPool.Get())
{
dplist1.AddRange(Dapper.SqlMapper.Query<xxx>(conn.Value, "select * from song limit 50").ToList());
}
}
Interlocked.Add(ref dplist1Count, dplist1.Count);
});
while (p1.IsCompleted == false) ;
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1Count}; ORM: Dapper");
}
[Table(Name = "song")]
class xxx {
public int Id { get; set; }
public string Title { get; set; }
//public string Url { get; set; }
public DateTime Create_time { get; set; }
public bool Is_deleted { get; set; }
}
}
[Table(Name = "song")]
class xxx
{
public int Id { get; set; }
public string Title { get; set; }
//public string Url { get; set; }
public DateTime Create_time { get; set; }
public bool Is_deleted { get; set; }
}
}
}

View File

@ -3,31 +3,32 @@ using System.Collections.Generic;
using System.Text;
public class g {
public class g
{
public static IFreeSql 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=100")
.UseAutoSyncStructure(false)
.Build();
public static IFreeSql 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=100")
.UseAutoSyncStructure(false)
.Build();
//public static IFreeSql sqlserver = new FreeSql.FreeSqlBuilder()
// .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=cms;Pooling=true;Max Pool Size=10")
// .UseAutoSyncStructure(false)
// .Build();
//public static IFreeSql sqlserver = new FreeSql.FreeSqlBuilder()
// .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=cms;Pooling=true;Max Pool Size=10")
// .UseAutoSyncStructure(false)
// .Build();
//public static IFreeSql pgsql = new FreeSql.FreeSqlBuilder()
// .UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=10")
// .UseAutoSyncStructure(false)
// .UseSyncStructureToLower(true)
// .Build();
//public static IFreeSql pgsql = new FreeSql.FreeSqlBuilder()
// .UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=10")
// .UseAutoSyncStructure(false)
// .UseSyncStructureToLower(true)
// .Build();
//public static IFreeSql oracle = new FreeSql.FreeSqlBuilder()
// .UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10")
// .UseAutoSyncStructure(false)
// .Build();
//public static IFreeSql oracle = new FreeSql.FreeSqlBuilder()
// .UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10")
// .UseAutoSyncStructure(false)
// .Build();
//public static IFreeSql sqlite = new FreeSql.FreeSqlBuilder()
// .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10")
// .UseAutoSyncStructure(false)
// .Build();
//public static IFreeSql sqlite = new FreeSql.FreeSqlBuilder()
// .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10")
// .UseAutoSyncStructure(false)
// .Build();
}

View File

@ -4,84 +4,93 @@ using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.MySqlConnector {
public class MySqlDeleteTest {
namespace FreeSql.Tests.MySqlConnector
{
public class MySqlDeleteTest
{
IDelete<Topic> delete => g.mysql.Delete<Topic>(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
IDelete<Topic> delete => g.mysql.Delete<Topic>(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
[Table(Name = "tb_topic")]
class Topic
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
[Fact]
public void Dywhere() {
Assert.Null(g.mysql.Delete<Topic>().ToSql());
var sql = g.mysql.Delete<Topic>(new[] { 1, 2 }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql);
[Fact]
public void Dywhere()
{
Assert.Null(g.mysql.Delete<Topic>().ToSql());
var sql = g.mysql.Delete<Topic>(new[] { 1, 2 }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new Topic { Id = 1, Title = "test" }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
sql = g.mysql.Delete<Topic>(new Topic { Id = 1, Title = "test" }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
sql = g.mysql.Delete<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new { id = 1 }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
}
sql = g.mysql.Delete<Topic>(new { id = 1 }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
}
[Fact]
public void Where() {
var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
[Fact]
public void Where()
{
var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (id = @id)", sql);
sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (id = @id)", sql);
var item = new Topic { Id = 1, Title = "newtitle" };
sql = delete.Where(item).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
var item = new Topic { Id = 1, Title = "newtitle" };
sql = delete.Where(item).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = delete.Where(items).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
}
[Fact]
public void WhereExists() {
sql = delete.Where(items).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
}
[Fact]
public void WhereExists()
{
}
[Fact]
public void ExecuteAffrows() {
}
[Fact]
public void ExecuteAffrows()
{
var id = g.mysql.Insert<Topic>(new Topic { Title = "xxxx" }).ExecuteIdentity();
Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows());
}
[Fact]
public void ExecuteDeleted() {
var id = g.mysql.Insert<Topic>(new Topic { Title = "xxxx" }).ExecuteIdentity();
Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows());
}
[Fact]
public void ExecuteDeleted()
{
//delete.Where(a => a.Id > 0).ExecuteDeleted();
}
//delete.Where(a => a.Id > 0).ExecuteDeleted();
}
[Fact]
public void AsTable() {
Assert.Null(g.mysql.Delete<Topic>().ToSql());
var sql = g.mysql.Delete<Topic>(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql);
[Fact]
public void AsTable()
{
Assert.Null(g.mysql.Delete<Topic>().ToSql());
var sql = g.mysql.Delete<Topic>(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql);
sql = g.mysql.Delete<Topic>(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql);
sql = g.mysql.Delete<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql);
}
}
sql = g.mysql.Delete<Topic>(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql);
}
}
}

View File

@ -4,132 +4,143 @@ using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.MySqlConnector {
public class MySqlInsertTest {
namespace FreeSql.Tests.MySqlConnector
{
public class MySqlInsertTest
{
IInsert<Topic> insert => g.mysql.Insert<Topic>(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
IInsert<Topic> insert => g.mysql.Insert<Topic>(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestEnumInsertTb {
[Column(IsIdentity = true)]
public int id { get; set; }
public TestEnumInserTbType type { get; set; }
public DateTime time { get; set; } = new DateTime();
}
enum TestEnumInserTbType { str1, biggit, sum211 }
[Fact]
public void AppendData() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
[Table(Name = "tb_topic")]
class Topic
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestEnumInsertTb
{
[Column(IsIdentity = true)]
public int id { get; set; }
public TestEnumInserTbType type { get; set; }
public DateTime time { get; set; } = new DateTime();
}
enum TestEnumInserTbType { str1, biggit, sum211 }
var sql = insert.AppendData(items.First()).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql);
[Fact]
public void AppendData()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = insert.AppendData(items).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql);
var sql = insert.AppendData(items.First()).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql);
sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql);
sql = insert.AppendData(items).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql);
sql = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211, time = DateTime.Now }).ToSql();
Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES(@type_0, @time_0)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql);
sql = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ToSql();
Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql);
}
sql = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211, time = DateTime.Now }).ToSql();
Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES(@type_0, @time_0)", sql);
[Fact]
public void InsertColumns() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ToSql();
Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql);
}
var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql);
[Fact]
public void InsertColumns()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = insert.AppendData(items).InsertColumns(a =>new { a.Title, a.Clicks }).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql);
}
[Fact]
public void IgnoreColumns() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql);
var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql);
}
[Fact]
public void IgnoreColumns()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`) VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql);
}
[Fact]
public void ExecuteAffrows() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now });
var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql);
Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows());
Assert.Equal(10, insert.AppendData(items).ExecuteAffrows());
sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`) VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql);
}
[Fact]
public void ExecuteAffrows()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now });
Assert.Equal(1, g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteAffrows());
Assert.Equal(1, g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteAffrows());
}
[Fact]
public void ExecuteIdentity() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows());
Assert.Equal(10, insert.AppendData(items).ExecuteAffrows());
Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity());
Assert.Equal(1, g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteAffrows());
Assert.Equal(1, g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteAffrows());
}
[Fact]
public void ExecuteIdentity()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
var id = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteIdentity();
Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select< TestEnumInsertTb>().Where(a => a.id == id).First()?.type);
id = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteIdentity();
Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select<TestEnumInsertTb>().Where(a => a.id == id).First()?.type);
}
[Fact]
public void ExecuteInserted() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity());
//insert.AppendData(items.First()).ExecuteInserted();
}
var id = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteIdentity();
Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select<TestEnumInsertTb>().Where(a => a.id == id).First()?.type);
id = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteIdentity();
Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select<TestEnumInsertTb>().Where(a => a.id == id).First()?.type);
}
[Fact]
public void ExecuteInserted()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
[Fact]
public void AsTable() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 });
//insert.AppendData(items.First()).ExecuteInserted();
}
var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql);
[Fact]
public void AsTable()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 });
sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql);
var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql);
sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql);
sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`) VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql);
}
}
sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`) VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql);
}
}
}

View File

@ -3,184 +3,199 @@ using System;
using System.Collections.Generic;
using Xunit;
namespace FreeSql.Tests.MySqlConnector {
public class MySqlUpdateTest {
IUpdate<Topic> update => g.mysql.Update<Topic>();
namespace FreeSql.Tests.MySqlConnector
{
public class MySqlUpdateTest
{
IUpdate<Topic> update => g.mysql.Update<Topic>();
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int? Clicks { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestEnumUpdateTb {
[Column(IsIdentity = true)]
public int id { get; set; }
public TestEnumUpdateTbType type { get; set; }
public DateTime time { get; set; } = new DateTime();
}
enum TestEnumUpdateTbType { str1, biggit, sum211 }
[Table(Name = "tb_topic")]
class Topic
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int? Clicks { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestEnumUpdateTb
{
[Column(IsIdentity = true)]
public int id { get; set; }
public TestEnumUpdateTbType type { get; set; }
public DateTime time { get; set; } = new DateTime();
}
enum TestEnumUpdateTbType { str1, biggit, sum211 }
[Fact]
public void Dywhere() {
Assert.Null(g.mysql.Update<Topic>().ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { 1, 2 }).SetRaw("title='test'").ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new { id = 1 }).SetRaw("title='test1'").ToSql());
}
[Fact]
public void Dywhere()
{
Assert.Null(g.mysql.Update<Topic>().ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { 1, 2 }).SetRaw("title='test'").ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new { id = 1 }).SetRaw("title='test1'").ToSql());
}
[Fact]
public void SetSource() {
var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = @p_0, `Title` = @p_1, `CreateTime` = @p_2 WHERE (`Id` = 1)", sql);
[Fact]
public void SetSource()
{
var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = @p_0, `Title` = @p_1, `CreateTime` = @p_2 WHERE (`Id` = 1)", sql);
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = update.SetSource(items).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = CASE `Id` WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END, `Title` = CASE `Id` WHEN 1 THEN @p_10 WHEN 2 THEN @p_11 WHEN 3 THEN @p_12 WHEN 4 THEN @p_13 WHEN 5 THEN @p_14 WHEN 6 THEN @p_15 WHEN 7 THEN @p_16 WHEN 8 THEN @p_17 WHEN 9 THEN @p_18 WHEN 10 THEN @p_19 END, `CreateTime` = CASE `Id` WHEN 1 THEN @p_20 WHEN 2 THEN @p_21 WHEN 3 THEN @p_22 WHEN 4 THEN @p_23 WHEN 5 THEN @p_24 WHEN 6 THEN @p_25 WHEN 7 THEN @p_26 WHEN 8 THEN @p_27 WHEN 9 THEN @p_28 WHEN 10 THEN @p_29 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = update.SetSource(items).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = CASE `Id` WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END, `Title` = CASE `Id` WHEN 1 THEN @p_10 WHEN 2 THEN @p_11 WHEN 3 THEN @p_12 WHEN 4 THEN @p_13 WHEN 5 THEN @p_14 WHEN 6 THEN @p_15 WHEN 7 THEN @p_16 WHEN 8 THEN @p_17 WHEN 9 THEN @p_18 WHEN 10 THEN @p_19 END, `CreateTime` = CASE `Id` WHEN 1 THEN @p_20 WHEN 2 THEN @p_21 WHEN 3 THEN @p_22 WHEN 4 THEN @p_23 WHEN 5 THEN @p_24 WHEN 6 THEN @p_25 WHEN 7 THEN @p_26 WHEN 8 THEN @p_27 WHEN 9 THEN @p_28 WHEN 10 THEN @p_29 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = CASE `Id` WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = CASE `Id` WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = update.SetSource(items).Set(a => a.CreateTime, new DateTime(2020,1,1)).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `CreateTime` = @p_0 WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = update.SetSource(items).Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `CreateTime` = @p_0 WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES(@type_0, @time_0)", sql);
var id = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0);
Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES(@type_0, @time_0)", sql);
var id = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0);
Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = @p_0, `time` = @p_1 WHERE (`id` = 0)", sql);
g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = @p_0, `time` = @p_1 WHERE (`id` = 0)", sql);
g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Insert<TestEnumUpdateTb>().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql);
id = g.mysql.Insert<TestEnumUpdateTb>().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0);
Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Insert<TestEnumUpdateTb>().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql);
id = g.mysql.Insert<TestEnumUpdateTb>().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0);
Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211', `time` = '0001-01-01 00:00:00.000' WHERE (`id` = 0)", sql);
g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
}
[Fact]
public void IgnoreColumns() {
var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0 WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211', `time` = '0001-01-01 00:00:00.000' WHERE (`id` = 0)", sql);
g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
}
[Fact]
public void IgnoreColumns()
{
var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0 WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = @p_0 WHERE (`id` = 0)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = @p_0 WHERE (`id` = 0)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
}
[Fact]
public void UpdateColumns() {
var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0 WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
}
[Fact]
public void UpdateColumns()
{
var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0 WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = @p_0 WHERE (`id` = 0)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = @p_0 WHERE (`id` = 0)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
}
[Fact]
public void Set() {
var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0 WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
}
[Fact]
public void Set()
{
var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0 WHERE (`Id` = 1)", sql);
sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0, `CreateTime` = @p_1 WHERE (`Id` = 1)", sql);
sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0, `CreateTime` = @p_1 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql);
int incrv = 10;
sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql);
int incrv = 10;
sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = `Clicks` * 10 / 1 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = `Clicks` * 10 / 1 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Id` = 10 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Id` = 10 WHERE (`Id` = 1)", sql);
var id = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0);
sql = g.mysql.Update<TestEnumUpdateTb>().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ToSql().Replace("\r\n", "");
Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = @p_0 WHERE (`id` = {id})", sql);
g.mysql.Update<TestEnumUpdateTb>().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
var id = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0);
sql = g.mysql.Update<TestEnumUpdateTb>().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ToSql().Replace("\r\n", "");
Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = @p_0 WHERE (`id` = {id})", sql);
g.mysql.Update<TestEnumUpdateTb>().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ToSql().Replace("\r\n", "");
Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = 'str1' WHERE (`id` = {id})", sql);
g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.str1, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
}
[Fact]
public void SetRaw() {
var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + @incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET clicks = clicks + @incrClick WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ToSql().Replace("\r\n", "");
Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = 'str1' WHERE (`id` = {id})", sql);
g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.str1, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
}
[Fact]
public void SetRaw()
{
var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + @incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET clicks = clicks + @incrClick WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == 0).SetRaw("`type` = {0}".FormatMySql(TestEnumUpdateTbType.sum211)).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
}
[Fact]
public void Where() {
var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == 0).SetRaw("`type` = {0}".FormatMySql(TestEnumUpdateTbType.sum211)).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
}
[Fact]
public void Where()
{
var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql);
sql = update.Where("id = @id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (id = @id)", sql);
sql = update.Where("id = @id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (id = @id)", sql);
var item = new Topic { Id = 1, Title = "newtitle" };
sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql);
var item = new Topic { Id = 1, Title = "newtitle" };
sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql);
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == 0 && a.type == TestEnumUpdateTbType.str1)
.Set(a => a.type, TestEnumUpdateTbType.sum211).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0 AND `type` = 'str1')", sql);
}
[Fact]
public void WhereExists() {
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == 0 && a.type == TestEnumUpdateTbType.str1)
.Set(a => a.type, TestEnumUpdateTbType.sum211).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0 AND `type` = 'str1')", sql);
}
[Fact]
public void WhereExists()
{
}
[Fact]
public void ExecuteAffrows() {
}
[Fact]
public void ExecuteAffrows()
{
}
[Fact]
public void ExecuteUpdated() {
}
[Fact]
public void ExecuteUpdated()
{
}
}
[Fact]
public void AsTable() {
Assert.Null(g.mysql.Update<Topic>().ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql());
}
}
[Fact]
public void AsTable()
{
Assert.Null(g.mysql.Update<Topic>().ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql());
}
}
}

View File

@ -3,252 +3,259 @@ using System;
using System.Numerics;
using Xunit;
namespace FreeSql.Tests.MySqlConnectorMapType {
public class EnumTest {
class EnumTestMap {
public Guid id { get; set; }
namespace FreeSql.Tests.MySqlConnectorMapType
{
public class EnumTest
{
class EnumTestMap
{
public Guid id { get; set; }
[Column(MapType = typeof(string))]
public ToStringMapEnum enum_to_string { get; set; }
[Column(MapType = typeof(string))]
public ToStringMapEnum? enumnullable_to_string { get; set; }
[Column(MapType = typeof(string))]
public ToStringMapEnum enum_to_string { get; set; }
[Column(MapType = typeof(string))]
public ToStringMapEnum? enumnullable_to_string { get; set; }
[Column(MapType = typeof(int))]
public ToStringMapEnum enum_to_int { get; set; }
[Column(MapType = typeof(int?))]
public ToStringMapEnum? enumnullable_to_int { get; set; }
}
public enum ToStringMapEnum { , abc, }
[Fact]
public void EnumToString() {
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
[Column(MapType = typeof(int))]
public ToStringMapEnum enum_to_int { get; set; }
[Column(MapType = typeof(int?))]
public ToStringMapEnum? enumnullable_to_int { get; set; }
}
public enum ToStringMapEnum { , abc, }
[Fact]
public void EnumToString()
{
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_string);
item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_string);
//update all
item.enum_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
//update all
item.enum_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
item.enum_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
item.enum_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_string);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_string);
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
[Fact]
public void EnumNullableToString() {
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Null(find.enumnullable_to_string);
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
[Fact]
public void EnumNullableToString()
{
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Null(find.enumnullable_to_string);
item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum. };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_string);
item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum. };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_string);
//update all
item.enumnullable_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_string);
//update all
item.enumnullable_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_string);
item.enumnullable_to_string = null;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Null(find.enumnullable_to_string);
item.enumnullable_to_string = null;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Null(find.enumnullable_to_string);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_string);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_string);
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
[Fact]
public void EnumToInt() {
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
[Fact]
public void EnumToInt()
{
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_int);
item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_int);
//update all
item.enum_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
//update all
item.enum_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
item.enum_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
item.enum_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_int);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_int);
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
[Fact]
public void EnumNullableToInt() {
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Null(find.enumnullable_to_int);
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
[Fact]
public void EnumNullableToInt()
{
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Null(find.enumnullable_to_int);
item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum. };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_int);
item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum. };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_int);
//update all
item.enumnullable_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_int);
//update all
item.enumnullable_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_int);
item.enumnullable_to_int = null;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Null(find.enumnullable_to_int);
item.enumnullable_to_int = null;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Null(find.enumnullable_to_int);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_int);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_int);
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
}
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
}
}

View File

@ -6,80 +6,91 @@ using System.Linq;
using System.Text;
using Xunit;
namespace FreeSql.Tests.MySqlConnector {
public class MySqlCodeFirstTest {
namespace FreeSql.Tests.MySqlConnector
{
public class MySqlCodeFirstTest
{
[Fact]
public void _字段() {
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<2>();
g.mysql.CodeFirst.SyncStructure<2>();
[Fact]
public void _字段()
{
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<2>();
g.mysql.CodeFirst.SyncStructure<2>();
var item = new 2 {
= "测试标题",
= DateTime.Now
};
Assert.Equal(1, g.mysql.Insert<2>().AppendData(item).ExecuteAffrows());
Assert.NotEqual(Guid.Empty, item.);
var item2 = g.mysql.Select<2>().Where(a => a. == item.).First();
Assert.NotNull(item2);
Assert.Equal(item., item2.);
Assert.Equal(item., item2.);
}
class 2 {
[Column(IsPrimary = true)]
public Guid { get; set; }
var item = new 2
{
= "测试标题",
= DateTime.Now
};
Assert.Equal(1, g.mysql.Insert<2>().AppendData(item).ExecuteAffrows());
Assert.NotEqual(Guid.Empty, item.);
var item2 = g.mysql.Select<2>().Where(a => a. == item.).First();
Assert.NotNull(item2);
Assert.Equal(item., item2.);
Assert.Equal(item., item2.);
}
class 2
{
[Column(IsPrimary = true)]
public Guid { get; set; }
public string { get; set; }
public string { get; set; }
public DateTime { get; set; }
}
public DateTime { get; set; }
}
[Fact]
public void AddUniques() {
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<AddUniquesInfo>();
g.mysql.CodeFirst.SyncStructure<AddUniquesInfo>();
}
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
class AddUniquesInfo {
public Guid id { get; set; }
[Column(Unique = "uk_phone")]
public string phone { get; set; }
[Fact]
public void AddUniques()
{
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<AddUniquesInfo>();
g.mysql.CodeFirst.SyncStructure<AddUniquesInfo>();
}
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
class AddUniquesInfo
{
public Guid id { get; set; }
[Column(Unique = "uk_phone")]
public string phone { get; set; }
[Column(Unique = "uk_group_index, uk_group_index22")]
public string group { get; set; }
[Column(Unique = "uk_group_index")]
public int index { get; set; }
[Column(Unique = "uk_group_index22")]
public string index22 { get; set; }
}
[Column(Unique = "uk_group_index, uk_group_index22")]
public string group { get; set; }
[Column(Unique = "uk_group_index")]
public int index { get; set; }
[Column(Unique = "uk_group_index22")]
public string index22 { get; set; }
}
[Fact]
public void AddField() {
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TopicAddField>();
[Fact]
public void AddField()
{
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TopicAddField>();
var id = g.mysql.Insert<TopicAddField>().AppendData(new TopicAddField { }).ExecuteIdentity();
}
var id = g.mysql.Insert<TopicAddField>().AppendData(new TopicAddField { }).ExecuteIdentity();
}
[Table(Name = "TopicAddField", OldName = "xxxtb.TopicAddField")]
public class TopicAddField {
[Column(IsIdentity = true)]
public int? Id { get; set; }
[Table(Name = "TopicAddField", OldName = "xxxtb.TopicAddField")]
public class TopicAddField
{
[Column(IsIdentity = true)]
public int? Id { get; set; }
public string name { get; set; }
public string name { get; set; }
[Column(DbType = "varchar(200) not null", OldName = "title")]
public string title222 { get; set; } = "10";
[Column(DbType = "varchar(200) not null", OldName = "title")]
public string title222 { get; set; } = "10";
[Column(IsIgnore = true)]
public DateTime ct { get; set; } = DateTime.Now;
}
[Column(IsIgnore = true)]
public DateTime ct { get; set; } = DateTime.Now;
}
[Fact]
public void GetComparisonDDLStatements() {
[Fact]
public void GetComparisonDDLStatements()
{
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TableAllType>();
if (string.IsNullOrEmpty(sql) == false) {
Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` (
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TableAllType>();
if (string.IsNullOrEmpty(sql) == false)
{
Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` (
`Id` INT(11) NOT NULL AUTO_INCREMENT,
`testFieldBool` BIT(1) NOT NULL,
`testFieldSByte` TINYINT(3) NOT NULL,
@ -126,352 +137,363 @@ namespace FreeSql.Tests.MySqlConnector {
PRIMARY KEY (`Id`)
) Engine=InnoDB;
", sql);
}
sql = g.mysql.CodeFirst.GetComparisonDDLStatements<Tb_alltype>();
}
IInsert<TableAllType> insert => g.mysql.Insert<TableAllType>();
ISelect<TableAllType> select => g.mysql.Select<TableAllType>();
[Fact]
public void CurdAllField() {
var item = new TableAllType { };
item.Id = (int)insert.AppendData(item).ExecuteIdentity();
var newitem = select.Where(a => a.Id == item.Id).ToOne();
var item2 = new TableAllType {
testFieldBool = true,
testFieldBoolNullable = true,
testFieldByte = 255,
testFieldByteNullable = 127,
testFieldBytes = Encoding.UTF8.GetBytes("我是中国人"),
testFieldDateTime = DateTime.Now,
testFieldDateTimeNullable = DateTime.Now.AddHours(-1),
testFieldDecimal = 99.99M,
testFieldDecimalNullable = 99.98M,
testFieldDouble = 999.99,
testFieldDoubleNullable = 999.98,
testFieldEnum1 = TableAllTypeEnumType1.e5,
testFieldEnum1Nullable = TableAllTypeEnumType1.e3,
testFieldEnum2 = TableAllTypeEnumType2.f2,
testFieldEnum2Nullable = TableAllTypeEnumType2.f3,
testFieldFloat = 19.99F,
testFieldFloatNullable = 19.98F,
testFieldGuid = Guid.NewGuid(),
testFieldGuidNullable = Guid.NewGuid(),
testFieldInt = int.MaxValue,
testFieldIntNullable = int.MinValue,
testFieldLineString = new MygisLineString(new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }),
testFieldLong = long.MaxValue,
testFieldMultiLineString = new MygisMultiLineString(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) },
new[] { new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 100) } }),
testFieldMultiPoint = new MygisMultiPoint(new[] { new MygisCoordinate2D(11, 11), new MygisCoordinate2D(51, 11) }),
testFieldMultiPolygon = new MygisMultiPolygon(new[] {
new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }),
new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }) }),
testFieldPoint = new MygisPoint(99, 99),
testFieldPolygon = new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }),
testFieldSByte = 100,
testFieldSByteNullable = 99,
testFieldShort = short.MaxValue,
testFieldShortNullable = short.MinValue,
testFieldString = "我是中国人string",
testFieldTimeSpan = TimeSpan.FromSeconds(999),
testFieldTimeSpanNullable = TimeSpan.FromSeconds(60),
testFieldUInt = uint.MaxValue,
testFieldUIntNullable = uint.MinValue,
testFieldULong = ulong.MaxValue,
testFieldULongNullable = ulong.MinValue,
testFieldUShort = ushort.MaxValue,
testFieldUShortNullable = ushort.MinValue,
testFielLongNullable = long.MinValue
};
item2.Id = (int)insert.AppendData(item2).ExecuteIdentity();
var newitem2 = select.Where(a => a.Id == item2.Id).ToOne();
}
sql = g.mysql.CodeFirst.GetComparisonDDLStatements<Tb_alltype>();
}
IInsert<TableAllType> insert => g.mysql.Insert<TableAllType>();
ISelect<TableAllType> select => g.mysql.Select<TableAllType>();
[Fact]
public void CurdAllField()
{
var item = new TableAllType { };
item.Id = (int)insert.AppendData(item).ExecuteIdentity();
var newitem = select.Where(a => a.Id == item.Id).ToOne();
var item2 = new TableAllType
{
testFieldBool = true,
testFieldBoolNullable = true,
testFieldByte = 255,
testFieldByteNullable = 127,
testFieldBytes = Encoding.UTF8.GetBytes("我是中国人"),
testFieldDateTime = DateTime.Now,
testFieldDateTimeNullable = DateTime.Now.AddHours(-1),
testFieldDecimal = 99.99M,
testFieldDecimalNullable = 99.98M,
testFieldDouble = 999.99,
testFieldDoubleNullable = 999.98,
testFieldEnum1 = TableAllTypeEnumType1.e5,
testFieldEnum1Nullable = TableAllTypeEnumType1.e3,
testFieldEnum2 = TableAllTypeEnumType2.f2,
testFieldEnum2Nullable = TableAllTypeEnumType2.f3,
testFieldFloat = 19.99F,
testFieldFloatNullable = 19.98F,
testFieldGuid = Guid.NewGuid(),
testFieldGuidNullable = Guid.NewGuid(),
testFieldInt = int.MaxValue,
testFieldIntNullable = int.MinValue,
testFieldLineString = new MygisLineString(new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }),
testFieldLong = long.MaxValue,
testFieldMultiLineString = new MygisMultiLineString(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) },
new[] { new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 100) } }),
testFieldMultiPoint = new MygisMultiPoint(new[] { new MygisCoordinate2D(11, 11), new MygisCoordinate2D(51, 11) }),
testFieldMultiPolygon = new MygisMultiPolygon(new[] {
new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }),
new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }) }),
testFieldPoint = new MygisPoint(99, 99),
testFieldPolygon = new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }),
testFieldSByte = 100,
testFieldSByteNullable = 99,
testFieldShort = short.MaxValue,
testFieldShortNullable = short.MinValue,
testFieldString = "我是中国人string",
testFieldTimeSpan = TimeSpan.FromSeconds(999),
testFieldTimeSpanNullable = TimeSpan.FromSeconds(60),
testFieldUInt = uint.MaxValue,
testFieldUIntNullable = uint.MinValue,
testFieldULong = ulong.MaxValue,
testFieldULongNullable = ulong.MinValue,
testFieldUShort = ushort.MaxValue,
testFieldUShortNullable = ushort.MinValue,
testFielLongNullable = long.MinValue
};
item2.Id = (int)insert.AppendData(item2).ExecuteIdentity();
var newitem2 = select.Where(a => a.Id == item2.Id).ToOne();
var items = select.ToList();
}
var items = select.ToList();
}
[JsonObject(MemberSerialization.OptIn), Table(Name = "tb_alltype")]
public partial class Tb_alltype {
[JsonObject(MemberSerialization.OptIn), Table(Name = "tb_alltype")]
public partial class Tb_alltype
{
[JsonProperty, Column(Name = "Id", DbType = "int(11)", IsPrimary = true, IsIdentity = true)]
public int Id { get; set; }
[JsonProperty, Column(Name = "Id", DbType = "int(11)", IsPrimary = true, IsIdentity = true)]
public int Id { get; set; }
[JsonProperty, Column(Name = "testFieldBool", DbType = "bit(1)")]
public bool TestFieldBool { get; set; }
[JsonProperty, Column(Name = "testFieldBool", DbType = "bit(1)")]
public bool TestFieldBool { get; set; }
[JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit(1)", IsNullable = true)]
public bool? TestFieldBoolNullable { get; set; }
[JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit(1)", IsNullable = true)]
public bool? TestFieldBoolNullable { get; set; }
[JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint(3) unsigned")]
public byte TestFieldByte { get; set; }
[JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint(3) unsigned")]
public byte TestFieldByte { get; set; }
[JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint(3) unsigned", IsNullable = true)]
public byte? TestFieldByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint(3) unsigned", IsNullable = true)]
public byte? TestFieldByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldBytes", DbType = "varbinary(255)", IsNullable = true)]
public byte[] TestFieldBytes { 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 = "testFieldDateTime", DbType = "datetime")]
public DateTime TestFieldDateTime { get; set; }
[JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)]
public DateTime? TestFieldDateTimeNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)]
public DateTime? TestFieldDateTimeNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDecimal", DbType = "decimal(10,2)")]
public decimal TestFieldDecimal { 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 = "testFieldDecimalNullable", DbType = "decimal(10,2)", IsNullable = true)]
public decimal? TestFieldDecimalNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDouble", DbType = "double")]
public double TestFieldDouble { get; set; }
[JsonProperty, Column(Name = "testFieldDouble", DbType = "double")]
public double TestFieldDouble { get; set; }
[JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "double", IsNullable = true)]
public double? TestFieldDoubleNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "double", IsNullable = true)]
public double? TestFieldDoubleNullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1", DbType = "enum('E1','E2','E3','E5')")]
public Tb_alltypeTESTFIELDENUM1 TestFieldEnum1 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1", DbType = "enum('E1','E2','E3','E5')")]
public Tb_alltypeTESTFIELDENUM1 TestFieldEnum1 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "enum('E1','E2','E3','E5')", IsNullable = true)]
public Tb_alltypeTESTFIELDENUM1NULLABLE? TestFieldEnum1Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "enum('E1','E2','E3','E5')", IsNullable = true)]
public Tb_alltypeTESTFIELDENUM1NULLABLE? TestFieldEnum1Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2", DbType = "set('F1','F2','F3')")]
public Tb_alltypeTESTFIELDENUM2 TestFieldEnum2 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2", DbType = "set('F1','F2','F3')")]
public Tb_alltypeTESTFIELDENUM2 TestFieldEnum2 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "set('F1','F2','F3')", IsNullable = true)]
public Tb_alltypeTESTFIELDENUM2NULLABLE? TestFieldEnum2Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "set('F1','F2','F3')", IsNullable = true)]
public Tb_alltypeTESTFIELDENUM2NULLABLE? TestFieldEnum2Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldFloat", DbType = "float")]
public float TestFieldFloat { get; set; }
[JsonProperty, Column(Name = "testFieldFloat", DbType = "float")]
public float TestFieldFloat { get; set; }
[JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "float", IsNullable = true)]
public float? TestFieldFloatNullable { get; set; }
[JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "float", IsNullable = true)]
public float? TestFieldFloatNullable { get; set; }
[JsonProperty, Column(Name = "testFieldGuid", DbType = "char(36)")]
public Guid TestFieldGuid { get; set; }
[JsonProperty, Column(Name = "testFieldGuid", DbType = "char(36)")]
public Guid TestFieldGuid { get; set; }
[JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "char(36)", IsNullable = true)]
public Guid? TestFieldGuidNullable { get; set; }
[JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "char(36)", IsNullable = true)]
public Guid? TestFieldGuidNullable { get; set; }
[JsonProperty, Column(Name = "testFieldInt", DbType = "int(11)")]
public int TestFieldInt { get; set; }
[JsonProperty, Column(Name = "testFieldInt", DbType = "int(11)")]
public int TestFieldInt { get; set; }
[JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int(11)", IsNullable = true)]
public int? TestFieldIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int(11)", IsNullable = true)]
public int? TestFieldIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldLineString", DbType = "linestring", IsNullable = true)]
public MygisGeometry TestFieldLineString { get; set; }
[JsonProperty, Column(Name = "testFieldLineString", DbType = "linestring", IsNullable = true)]
public MygisGeometry TestFieldLineString { get; set; }
[JsonProperty, Column(Name = "testFieldLong", DbType = "bigint(20)")]
public long TestFieldLong { get; set; }
[JsonProperty, Column(Name = "testFieldLong", DbType = "bigint(20)")]
public long TestFieldLong { get; set; }
[JsonProperty, Column(Name = "testFieldMultiLineString", DbType = "multilinestring", IsNullable = true)]
public MygisGeometry TestFieldMultiLineString { get; set; }
[JsonProperty, Column(Name = "testFieldMultiLineString", DbType = "multilinestring", IsNullable = true)]
public MygisGeometry TestFieldMultiLineString { get; set; }
[JsonProperty, Column(Name = "testFieldMultiPoint", DbType = "multipoint", IsNullable = true)]
public MygisGeometry TestFieldMultiPoint { get; set; }
[JsonProperty, Column(Name = "testFieldMultiPoint", DbType = "multipoint", IsNullable = true)]
public MygisGeometry TestFieldMultiPoint { get; set; }
[JsonProperty, Column(Name = "testFieldMultiPolygon", DbType = "multipolygon", IsNullable = true)]
public MygisGeometry TestFieldMultiPolygon { get; set; }
[JsonProperty, Column(Name = "testFieldMultiPolygon", DbType = "multipolygon", IsNullable = true)]
public MygisGeometry TestFieldMultiPolygon { get; set; }
[JsonProperty, Column(Name = "testFieldPoint", DbType = "point", IsNullable = true)]
public MygisGeometry TestFieldPoint { get; set; }
[JsonProperty, Column(Name = "testFieldPoint", DbType = "point", IsNullable = true)]
public MygisGeometry TestFieldPoint { get; set; }
[JsonProperty, Column(Name = "testFieldPolygon", DbType = "polygon", IsNullable = true)]
public MygisGeometry TestFieldPolygon { get; set; }
[JsonProperty, Column(Name = "testFieldPolygon", DbType = "polygon", IsNullable = true)]
public MygisGeometry TestFieldPolygon { get; set; }
[JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint(3)")]
public sbyte TestFieldSByte { get; set; }
[JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint(3)")]
public sbyte TestFieldSByte { get; set; }
[JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint(3)", IsNullable = true)]
public sbyte? TestFieldSByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint(3)", IsNullable = true)]
public sbyte? TestFieldSByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldShort", DbType = "smallint(6)")]
public short TestFieldShort { get; set; }
[JsonProperty, Column(Name = "testFieldShort", DbType = "smallint(6)")]
public short TestFieldShort { get; set; }
[JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint(6)", IsNullable = true)]
public short? TestFieldShortNullable { get; set; }
[JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint(6)", IsNullable = true)]
public short? TestFieldShortNullable { get; set; }
[JsonProperty, Column(Name = "testFieldString", DbType = "varchar(255)", IsNullable = true)]
public string TestFieldString { get; set; }
[JsonProperty, Column(Name = "testFieldString", DbType = "varchar(255)", IsNullable = true)]
public string TestFieldString { get; set; }
[JsonProperty, Column(Name = "testFieldTimeSpan", DbType = "time")]
public TimeSpan TestFieldTimeSpan { 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 = "testFieldTimeSpanNullable", DbType = "time", IsNullable = true)]
public TimeSpan? TestFieldTimeSpanNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUInt", DbType = "int(10) unsigned")]
public uint TestFieldUInt { get; set; }
[JsonProperty, Column(Name = "testFieldUInt", DbType = "int(10) unsigned")]
public uint TestFieldUInt { get; set; }
[JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int(10) unsigned", IsNullable = true)]
public uint? TestFieldUIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int(10) unsigned", IsNullable = true)]
public uint? TestFieldUIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldULong", DbType = "bigint(20) unsigned")]
public ulong TestFieldULong { get; set; }
[JsonProperty, Column(Name = "testFieldULong", DbType = "bigint(20) unsigned")]
public ulong TestFieldULong { get; set; }
[JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint(20) unsigned", IsNullable = true)]
public ulong? TestFieldULongNullable { get; set; }
[JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint(20) unsigned", IsNullable = true)]
public ulong? TestFieldULongNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint(5) unsigned")]
public ushort TestFieldUShort { get; set; }
[JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint(5) unsigned")]
public ushort TestFieldUShort { get; set; }
[JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint(5) unsigned", IsNullable = true)]
public ushort? TestFieldUShortNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint(5) unsigned", IsNullable = true)]
public ushort? TestFieldUShortNullable { get; set; }
[JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint(20)", IsNullable = true)]
public long? TestFielLongNullable { get; set; }
[JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint(20)", IsNullable = true)]
public long? TestFielLongNullable { get; set; }
internal static IFreeSql mysql => null;
public static FreeSql.ISelect<Tb_alltype> Select => mysql.Select<Tb_alltype>();
internal static IFreeSql mysql => null;
public static FreeSql.ISelect<Tb_alltype> Select => mysql.Select<Tb_alltype>();
public static long Delete(int Id) {
var affrows = mysql.Delete<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows();
return affrows;
}
public static long Delete(int Id)
{
var affrows = mysql.Delete<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows();
return affrows;
}
/// <summary>
/// 保存或添加,如果主键有值则尝试 Update如果影响的行为 0 则尝试 Insert
/// </summary>
public void Save() {
if (this.Id != default(int)) {
var affrows = mysql.Update<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows();
if (affrows > 0) return;
}
this.Id = (int)mysql.Insert<Tb_alltype>().AppendData(this).ExecuteIdentity();
}
/// <summary>
/// 保存或添加,如果主键有值则尝试 Update如果影响的行为 0 则尝试 Insert
/// </summary>
public void Save()
{
if (this.Id != default(int))
{
var affrows = mysql.Update<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows();
if (affrows > 0) return;
}
this.Id = (int)mysql.Insert<Tb_alltype>().AppendData(this).ExecuteIdentity();
}
}
}
public enum Tb_alltypeTESTFIELDENUM1 {
E1 = 1, E2, E3, E5
}
public enum Tb_alltypeTESTFIELDENUM1NULLABLE {
E1 = 1, E2, E3, E5
}
[Flags]
public enum Tb_alltypeTESTFIELDENUM2 : long {
F1 = 1, F2 = 2, F3 = 4
}
[Flags]
public enum Tb_alltypeTESTFIELDENUM2NULLABLE : long {
F1 = 1, F2 = 2, F3 = 4
}
public enum Tb_alltypeTESTFIELDENUM1
{
E1 = 1, E2, E3, E5
}
public enum Tb_alltypeTESTFIELDENUM1NULLABLE
{
E1 = 1, E2, E3, E5
}
[Flags]
public enum Tb_alltypeTESTFIELDENUM2 : long
{
F1 = 1, F2 = 2, F3 = 4
}
[Flags]
public enum Tb_alltypeTESTFIELDENUM2NULLABLE : long
{
F1 = 1, F2 = 2, F3 = 4
}
[Table(Name = "tb_alltype")]
class TableAllType {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public bool testFieldBool { get; set; }
public sbyte testFieldSByte { get; set; }
public short testFieldShort { get; set; }
public int testFieldInt { get; set; }
public long testFieldLong { get; set; }
public byte testFieldByte { get; set; }
public ushort testFieldUShort { get; set; }
public uint testFieldUInt { get; set; }
public ulong testFieldULong { get; set; }
public double testFieldDouble { get; set; }
public float testFieldFloat { get; set; }
public decimal testFieldDecimal { get; set; }
public TimeSpan testFieldTimeSpan { get; set; }
public DateTime testFieldDateTime { get; set; }
public byte[] testFieldBytes { get; set; }
public string testFieldString { get; set; }
public Guid testFieldGuid { get; set; }
public bool? testFieldBoolNullable { get; set; }
public sbyte? testFieldSByteNullable { get; set; }
public short? testFieldShortNullable { get; set; }
public int? testFieldIntNullable { get; set; }
public long? testFielLongNullable { get; set; }
public byte? testFieldByteNullable { get; set; }
public ushort? testFieldUShortNullable { get; set; }
public uint? testFieldUIntNullable { get; set; }
public ulong? testFieldULongNullable { get; set; }
public double? testFieldDoubleNullable { get; set; }
public float? testFieldFloatNullable { get; set; }
public decimal? testFieldDecimalNullable { get; set; }
public TimeSpan? testFieldTimeSpanNullable { get; set; }
public DateTime? testFieldDateTimeNullable { get; set; }
public Guid? testFieldGuidNullable { get; set; }
public MygisPoint testFieldPoint { get; set; }
public MygisLineString testFieldLineString { get; set; }
public MygisPolygon testFieldPolygon { get; set; }
public MygisMultiPoint testFieldMultiPoint { get; set; }
public MygisMultiLineString testFieldMultiLineString { get; set; }
public MygisMultiPolygon testFieldMultiPolygon { get; set; }
public TableAllTypeEnumType1 testFieldEnum1 { get; set; }
public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; }
public TableAllTypeEnumType2 testFieldEnum2 { get; set; }
public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; }
}
public enum TableAllTypeEnumType1 { e1, e2, e3, e5 }
[Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 }
}
[Table(Name = "tb_alltype")]
class TableAllType
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public bool testFieldBool { get; set; }
public sbyte testFieldSByte { get; set; }
public short testFieldShort { get; set; }
public int testFieldInt { get; set; }
public long testFieldLong { get; set; }
public byte testFieldByte { get; set; }
public ushort testFieldUShort { get; set; }
public uint testFieldUInt { get; set; }
public ulong testFieldULong { get; set; }
public double testFieldDouble { get; set; }
public float testFieldFloat { get; set; }
public decimal testFieldDecimal { get; set; }
public TimeSpan testFieldTimeSpan { get; set; }
public DateTime testFieldDateTime { get; set; }
public byte[] testFieldBytes { get; set; }
public string testFieldString { get; set; }
public Guid testFieldGuid { get; set; }
public bool? testFieldBoolNullable { get; set; }
public sbyte? testFieldSByteNullable { get; set; }
public short? testFieldShortNullable { get; set; }
public int? testFieldIntNullable { get; set; }
public long? testFielLongNullable { get; set; }
public byte? testFieldByteNullable { get; set; }
public ushort? testFieldUShortNullable { get; set; }
public uint? testFieldUIntNullable { get; set; }
public ulong? testFieldULongNullable { get; set; }
public double? testFieldDoubleNullable { get; set; }
public float? testFieldFloatNullable { get; set; }
public decimal? testFieldDecimalNullable { get; set; }
public TimeSpan? testFieldTimeSpanNullable { get; set; }
public DateTime? testFieldDateTimeNullable { get; set; }
public Guid? testFieldGuidNullable { get; set; }
public MygisPoint testFieldPoint { get; set; }
public MygisLineString testFieldLineString { get; set; }
public MygisPolygon testFieldPolygon { get; set; }
public MygisMultiPoint testFieldMultiPoint { get; set; }
public MygisMultiLineString testFieldMultiLineString { get; set; }
public MygisMultiPolygon testFieldMultiPolygon { get; set; }
public TableAllTypeEnumType1 testFieldEnum1 { get; set; }
public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; }
public TableAllTypeEnumType2 testFieldEnum2 { get; set; }
public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; }
}
public enum TableAllTypeEnumType1 { e1, e2, e3, e5 }
[Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 }
}
}

View File

@ -2,53 +2,64 @@ using FreeSql.DataAnnotations;
using System;
using Xunit;
namespace FreeSql.Tests.MySqlConnector {
public class MySqlAdoTest {
[Fact]
public void Pool() {
var t1 = g.mysql.Ado.MasterPool.StatisticsFullily;
}
namespace FreeSql.Tests.MySqlConnector
{
public class MySqlAdoTest
{
[Fact]
public void Pool()
{
var t1 = g.mysql.Ado.MasterPool.StatisticsFullily;
}
[Fact]
public void SlavePools() {
var t2 = g.mysql.Ado.SlavePools.Count;
}
[Fact]
public void SlavePools()
{
var t2 = g.mysql.Ado.SlavePools.Count;
}
[Fact]
public void ExecuteReader() {
}
[Fact]
public void ExecuteArray() {
}
[Fact]
public void ExecuteNonQuery() {
}
[Fact]
public void ExecuteScalar() {
}
[Fact]
public void ExecuteReader()
{
[Fact]
public void Query() {
var t3 = g.mysql.Ado.Query<xxx>("select * from song");
}
[Fact]
public void ExecuteArray()
{
var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song");
}
[Fact]
public void ExecuteNonQuery()
{
var t5 = g.mysql.Ado.Query<dynamic>("select * from song");
}
}
[Fact]
public void ExecuteScalar()
{
[Fact]
public void QueryMultipline() {
var t3 = g.mysql.Ado.Query<xxx, (int, string, string), dynamic>("select * from song; select * from song; select * from song");
}
}
class xxx {
public int Id { get; set; }
public string Path { get; set; }
public string Title2 { get; set; }
}
}
[Fact]
public void Query()
{
var t3 = g.mysql.Ado.Query<xxx>("select * from song");
var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song");
var t5 = g.mysql.Ado.Query<dynamic>("select * from song");
}
[Fact]
public void QueryMultipline()
{
var t3 = g.mysql.Ado.Query<xxx, (int, string, string), dynamic>("select * from song; select * from song; select * from song");
}
class xxx
{
public int Id { get; set; }
public string Path { get; set; }
public string Title2 { get; set; }
}
}
}

View File

@ -4,143 +4,166 @@ using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.MySqlConnectorExpression {
public class ConvertTest {
namespace FreeSql.Tests.MySqlConnectorExpression
{
public class ConvertTest
{
ISelect<Topic> select => g.mysql.Select<Topic>();
ISelect<Topic> select => g.mysql.Select<Topic>();
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public int TypeGuid { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestTypeInfo {
public int Guid { get; set; }
public int ParentId { get; set; }
public TestTypeParentInfo Parent { get; set; }
public string Name { get; set; }
}
class TestTypeParentInfo {
public int Id { get; set; }
public string Name { get; set; }
[Table(Name = "tb_topic")]
class Topic
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public int TypeGuid { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestTypeInfo
{
public int Guid { get; set; }
public int ParentId { get; set; }
public TestTypeParentInfo Parent { get; set; }
public string Name { get; set; }
}
class TestTypeParentInfo
{
public int Id { get; set; }
public string Name { get; set; }
public List<TestTypeInfo> Types { get; set; }
}
public List<TestTypeInfo> Types { get; set; }
}
[Fact]
public void ToBoolean() {
var data = new List<object>();
data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList());
data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList());
}
[Fact]
public void ToByte() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList());
data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList());
}
[Fact]
public void ToChar() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList());
data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList());
}
[Fact]
public void ToDateTime() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList());
data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList());
}
[Fact]
public void ToDecimal() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList());
data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToDouble() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList());
data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToInt16() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList());
data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToInt32() {
var data = new List<object>();
data.Add(select.Where(a => (int)a.Clicks > 0).ToList());
data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList());
data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToInt64() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList());
data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToSByte() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList());
data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList());
}
[Fact]
public void ToSingle() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList());
data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void this_ToString() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList());
data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList());
}
[Fact]
public void ToUInt16() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList());
data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToUInt32() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList());
data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToUInt64() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList());
data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToBoolean()
{
var data = new List<object>();
data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList());
data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList());
}
[Fact]
public void ToByte()
{
var data = new List<object>();
data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList());
data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList());
}
[Fact]
public void ToChar()
{
var data = new List<object>();
data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList());
data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList());
}
[Fact]
public void ToDateTime()
{
var data = new List<object>();
data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList());
data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList());
}
[Fact]
public void ToDecimal()
{
var data = new List<object>();
data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList());
data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToDouble()
{
var data = new List<object>();
data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList());
data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToInt16()
{
var data = new List<object>();
data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList());
data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToInt32()
{
var data = new List<object>();
data.Add(select.Where(a => (int)a.Clicks > 0).ToList());
data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList());
data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToInt64()
{
var data = new List<object>();
data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList());
data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToSByte()
{
var data = new List<object>();
data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList());
data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList());
}
[Fact]
public void ToSingle()
{
var data = new List<object>();
data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList());
data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void this_ToString()
{
var data = new List<object>();
data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList());
data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList());
}
[Fact]
public void ToUInt16()
{
var data = new List<object>();
data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList());
data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToUInt32()
{
var data = new List<object>();
data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList());
data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void ToUInt64()
{
var data = new List<object>();
data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList());
data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList());
}
[Fact]
public void Guid_Parse() {
var data = new List<object>();
data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList());
}
[Fact]
public void Guid_Parse()
{
var data = new List<object>();
data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList());
}
[Fact]
public void Guid_NewGuid() {
var data = new List<object>();
//data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList());
}
[Fact]
public void Guid_NewGuid()
{
var data = new List<object>();
//data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList());
}
[Fact]
public void Random() {
var data = new List<object>();
data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList());
data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList());
}
}
[Fact]
public void Random()
{
var data = new List<object>();
data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList());
data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList());
}
}
}

View File

@ -4,129 +4,153 @@ using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.MySqlConnectorExpression {
public class MathTest {
namespace FreeSql.Tests.MySqlConnectorExpression
{
public class MathTest
{
ISelect<Topic> select => g.mysql.Select<Topic>();
ISelect<Topic> select => g.mysql.Select<Topic>();
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public int TypeGuid { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestTypeInfo {
public int Guid { get; set; }
public int ParentId { get; set; }
public TestTypeParentInfo Parent { get; set; }
public string Name { get; set; }
}
class TestTypeParentInfo {
public int Id { get; set; }
public string Name { get; set; }
[Table(Name = "tb_topic")]
class Topic
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public int TypeGuid { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestTypeInfo
{
public int Guid { get; set; }
public int ParentId { get; set; }
public TestTypeParentInfo Parent { get; set; }
public string Name { get; set; }
}
class TestTypeParentInfo
{
public int Id { get; set; }
public string Name { get; set; }
public List<TestTypeInfo> Types { get; set; }
}
public List<TestTypeInfo> Types { get; set; }
}
[Fact]
public void PI() {
var data = new List<object>();
data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList());
}
[Fact]
public void Abs() {
var data = new List<object>();
data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList());
}
[Fact]
public void Sign() {
var data = new List<object>();
data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList());
}
[Fact]
public void Floor() {
var data = new List<object>();
data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList());
}
[Fact]
public void Ceiling() {
var data = new List<object>();
data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList());
}
[Fact]
public void Round() {
var data = new List<object>();
data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList());
data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList());
}
[Fact]
public void Exp() {
var data = new List<object>();
data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList());
}
[Fact]
public void Log() {
var data = new List<object>();
data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList());
}
[Fact]
public void Log10() {
var data = new List<object>();
data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList());
}
[Fact]
public void Pow() {
var data = new List<object>();
data.Add(select.Where(a => Math.Pow(2, a.Clicks) == a.Clicks + 1).ToList());
}
[Fact]
public void Sqrt() {
var data = new List<object>();
data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Cos() {
var data = new List<object>();
data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Sin() {
var data = new List<object>();
data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Tan() {
var data = new List<object>();
data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Acos() {
var data = new List<object>();
data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Asin() {
var data = new List<object>();
data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Atan() {
var data = new List<object>();
data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Atan2() {
var data = new List<object>();
data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList());
}
[Fact]
public void Truncate() {
var data = new List<object>();
data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList());
}
}
[Fact]
public void PI()
{
var data = new List<object>();
data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList());
}
[Fact]
public void Abs()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList());
}
[Fact]
public void Sign()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList());
}
[Fact]
public void Floor()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList());
}
[Fact]
public void Ceiling()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList());
}
[Fact]
public void Round()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList());
data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList());
}
[Fact]
public void Exp()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList());
}
[Fact]
public void Log()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList());
}
[Fact]
public void Log10()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList());
}
[Fact]
public void Pow()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Pow(2, a.Clicks) == a.Clicks + 1).ToList());
}
[Fact]
public void Sqrt()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Cos()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Sin()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Tan()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Acos()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Asin()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Atan()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
}
[Fact]
public void Atan2()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList());
}
[Fact]
public void Truncate()
{
var data = new List<object>();
data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList());
}
}
}

View File

@ -5,117 +5,123 @@ using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.MySqlConnectorExpression {
public class OtherTest {
namespace FreeSql.Tests.MySqlConnectorExpression
{
public class OtherTest
{
ISelect<TableAllType> select => g.mysql.Select<TableAllType>();
ISelect<TableAllType> select => g.mysql.Select<TableAllType>();
public OtherTest() {
}
public OtherTest()
{
[Fact]
public void Boolean() {
var t1 = select.Where(a => a.testFieldBool == true).ToList();
var t2 = select.Where(a => a.testFieldBool != true).ToList();
var t3 = select.Where(a => a.testFieldBool == false).ToList();
var t4 = select.Where(a => !a.testFieldBool).ToList();
var t5 = select.Where(a => a.testFieldBool).ToList();
}
var t11 = select.Where(a => a.testFieldBoolNullable == true).ToList();
var t22 = select.Where(a => a.testFieldBoolNullable != true).ToList();
var t33 = select.Where(a => a.testFieldBoolNullable == false).ToList();
var t44 = select.Where(a => !a.testFieldBoolNullable.Value).ToList();
var t55 = select.Where(a => a.testFieldBoolNullable.Value).ToList();
}
[Fact]
public void Boolean()
{
var t1 = select.Where(a => a.testFieldBool == true).ToList();
var t2 = select.Where(a => a.testFieldBool != true).ToList();
var t3 = select.Where(a => a.testFieldBool == false).ToList();
var t4 = select.Where(a => !a.testFieldBool).ToList();
var t5 = select.Where(a => a.testFieldBool).ToList();
[Fact]
public void Array() {
int[] nullarr = null;
Assert.Throws<MySqlException>(() => { select.Where(a => nullarr.Contains(a.testFieldInt)).ToList(); });
Assert.Throws<MySqlException>(() => { select.Where(a => new int[0].Contains(a.testFieldInt)).ToList(); });
var t11 = select.Where(a => a.testFieldBoolNullable == true).ToList();
var t22 = select.Where(a => a.testFieldBoolNullable != true).ToList();
var t33 = select.Where(a => a.testFieldBoolNullable == false).ToList();
var t44 = select.Where(a => !a.testFieldBoolNullable.Value).ToList();
var t55 = select.Where(a => a.testFieldBoolNullable.Value).ToList();
}
IEnumerable<int> testlinqlist = new List<int>(new[] { 1, 2, 3 });
var testlinq = select.Where(a => testlinqlist.Contains(a.testFieldInt)).ToList();
[Fact]
public void Array()
{
int[] nullarr = null;
Assert.Throws<MySqlException>(() => { select.Where(a => nullarr.Contains(a.testFieldInt)).ToList(); });
Assert.Throws<MySqlException>(() => { select.Where(a => new int[0].Contains(a.testFieldInt)).ToList(); });
//in not in
var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList();
var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList();
var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList();
IEnumerable<int> testlinqlist = new List<int>(new[] { 1, 2, 3 });
var testlinq = select.Where(a => testlinqlist.Contains(a.testFieldInt)).ToList();
var inarray = new[] { 1, 2, 3 };
var sql1111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList();
var sql1122 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList();
var sql1133 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList();
//in not in
var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList();
var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList();
var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList();
//in not in
var sql11111 = select.Where(a => new List<int>() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList();
var sql11222 = select.Where(a => new List<int>() { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList();
var sql11333 = select.Where(a => !new List<int>() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList();
var inarray = new[] { 1, 2, 3 };
var sql1111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList();
var sql1122 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList();
var sql1133 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList();
var sql11111a = select.Where(a => new List<int>(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList();
var sql11222b = select.Where(a => new List<int>(new[] { 1, 2, 3 }).Contains(a.testFieldInt) == false).ToList();
var sql11333c = select.Where(a => !new List<int>(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList();
//in not in
var sql11111 = select.Where(a => new List<int>() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList();
var sql11222 = select.Where(a => new List<int>() { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList();
var sql11333 = select.Where(a => !new List<int>() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList();
var inarray2 = new List<int>() { 1, 2, 3 };
var sql111111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList();
var sql112222 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList();
var sql113333 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList();
}
var sql11111a = select.Where(a => new List<int>(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList();
var sql11222b = select.Where(a => new List<int>(new[] { 1, 2, 3 }).Contains(a.testFieldInt) == false).ToList();
var sql11333c = select.Where(a => !new List<int>(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList();
[Table(Name = "tb_alltype")]
class TableAllType {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
var inarray2 = new List<int>() { 1, 2, 3 };
var sql111111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList();
var sql112222 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList();
var sql113333 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList();
}
public bool testFieldBool { get; set; }
public sbyte testFieldSByte { get; set; }
public short testFieldShort { get; set; }
public int testFieldInt { get; set; }
public long testFieldLong { get; set; }
public byte testFieldByte { get; set; }
public ushort testFieldUShort { get; set; }
public uint testFieldUInt { get; set; }
public ulong testFieldULong { get; set; }
public double testFieldDouble { get; set; }
public float testFieldFloat { get; set; }
public decimal testFieldDecimal { get; set; }
public TimeSpan testFieldTimeSpan { get; set; }
public DateTime testFieldDateTime { get; set; }
public byte[] testFieldBytes { get; set; }
public string testFieldString { get; set; }
public Guid testFieldGuid { get; set; }
[Table(Name = "tb_alltype")]
class TableAllType
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public bool? testFieldBoolNullable { get; set; }
public sbyte? testFieldSByteNullable { get; set; }
public short? testFieldShortNullable { get; set; }
public int? testFieldIntNullable { get; set; }
public long? testFielLongNullable { get; set; }
public byte? testFieldByteNullable { get; set; }
public ushort? testFieldUShortNullable { get; set; }
public uint? testFieldUIntNullable { get; set; }
public ulong? testFieldULongNullable { get; set; }
public double? testFieldDoubleNullable { get; set; }
public float? testFieldFloatNullable { get; set; }
public decimal? testFieldDecimalNullable { get; set; }
public TimeSpan? testFieldTimeSpanNullable { get; set; }
public DateTime? testFieldDateTimeNullable { get; set; }
public Guid? testFieldGuidNullable { get; set; }
public bool testFieldBool { get; set; }
public sbyte testFieldSByte { get; set; }
public short testFieldShort { get; set; }
public int testFieldInt { get; set; }
public long testFieldLong { get; set; }
public byte testFieldByte { get; set; }
public ushort testFieldUShort { get; set; }
public uint testFieldUInt { get; set; }
public ulong testFieldULong { get; set; }
public double testFieldDouble { get; set; }
public float testFieldFloat { get; set; }
public decimal testFieldDecimal { get; set; }
public TimeSpan testFieldTimeSpan { get; set; }
public DateTime testFieldDateTime { get; set; }
public byte[] testFieldBytes { get; set; }
public string testFieldString { get; set; }
public Guid testFieldGuid { get; set; }
public MygisPoint testFieldPoint { get; set; }
public MygisLineString testFieldLineString { get; set; }
public MygisPolygon testFieldPolygon { get; set; }
public MygisMultiPoint testFieldMultiPoint { get; set; }
public MygisMultiLineString testFieldMultiLineString { get; set; }
public MygisMultiPolygon testFieldMultiPolygon { get; set; }
public bool? testFieldBoolNullable { get; set; }
public sbyte? testFieldSByteNullable { get; set; }
public short? testFieldShortNullable { get; set; }
public int? testFieldIntNullable { get; set; }
public long? testFielLongNullable { get; set; }
public byte? testFieldByteNullable { get; set; }
public ushort? testFieldUShortNullable { get; set; }
public uint? testFieldUIntNullable { get; set; }
public ulong? testFieldULongNullable { get; set; }
public double? testFieldDoubleNullable { get; set; }
public float? testFieldFloatNullable { get; set; }
public decimal? testFieldDecimalNullable { get; set; }
public TimeSpan? testFieldTimeSpanNullable { get; set; }
public DateTime? testFieldDateTimeNullable { get; set; }
public Guid? testFieldGuidNullable { get; set; }
public TableAllTypeEnumType1 testFieldEnum1 { get; set; }
public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; }
public TableAllTypeEnumType2 testFieldEnum2 { get; set; }
public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; }
}
public MygisPoint testFieldPoint { get; set; }
public MygisLineString testFieldLineString { get; set; }
public MygisPolygon testFieldPolygon { get; set; }
public MygisMultiPoint testFieldMultiPoint { get; set; }
public MygisMultiLineString testFieldMultiLineString { get; set; }
public MygisMultiPolygon testFieldMultiPolygon { get; set; }
public enum TableAllTypeEnumType1 { e1, e2, e3, e5 }
[Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 }
}
public TableAllTypeEnumType1 testFieldEnum1 { get; set; }
public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; }
public TableAllTypeEnumType2 testFieldEnum2 { get; set; }
public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; }
}
public enum TableAllTypeEnumType1 { e1, e2, e3, e5 }
[Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 }
}
}

View File

@ -4,257 +4,290 @@ using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.MySqlConnectorExpression {
public class TimeSpanTest {
namespace FreeSql.Tests.MySqlConnectorExpression
{
public class TimeSpanTest
{
ISelect<Topic> select => g.mysql.Select<Topic>();
ISelect<Topic> select => g.mysql.Select<Topic>();
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public int TypeGuid { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestTypeInfo {
public int Guid { get; set; }
public int ParentId { get; set; }
public TestTypeParentInfo Parent { get; set; }
public string Name { get; set; }
}
class TestTypeParentInfo {
public int Id { get; set; }
public string Name { get; set; }
[Table(Name = "tb_topic")]
class Topic
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public int TypeGuid { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestTypeInfo
{
public int Guid { get; set; }
public int ParentId { get; set; }
public TestTypeParentInfo Parent { get; set; }
public string Name { get; set; }
}
class TestTypeParentInfo
{
public int Id { get; set; }
public string Name { get; set; }
public List<TestTypeInfo> Types { get; set; }
}
[Fact]
public void Zero() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > 0)
}
[Fact]
public void MinValue() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580)
}
[Fact]
public void MaxValue() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580)
}
[Fact]
public void Days() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0)
}
[Fact]
public void Hours() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0)
}
[Fact]
public void Milliseconds() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0)
}
[Fact]
public void Minutes() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 60000000 mod 60) > 0)
}
[Fact]
public void Seconds() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0)
}
[Fact]
public void Ticks() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) * 10) > 0)
}
[Fact]
public void TotalDays() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0)
}
[Fact]
public void TotalHours() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0)
}
[Fact]
public void TotalMilliseconds() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0)
}
[Fact]
public void TotalMinutes() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0)
}
[Fact]
public void TotalSeconds() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0)
}
[Fact]
public void Add() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0)
}
[Fact]
public void Subtract() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) - (1 * 86400000000)) > 0)
}
[Fact]
public void CompareTo() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0)
}
[Fact]
public void this_Equals() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000)))
}
[Fact]
public void this_ToString() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') = 'ssss')
}
public List<TestTypeInfo> Types { get; set; }
}
[Fact]
public void Zero()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > 0)
}
[Fact]
public void MinValue()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580)
}
[Fact]
public void MaxValue()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580)
}
[Fact]
public void Days()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0)
}
[Fact]
public void Hours()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0)
}
[Fact]
public void Milliseconds()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0)
}
[Fact]
public void Minutes()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 60000000 mod 60) > 0)
}
[Fact]
public void Seconds()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0)
}
[Fact]
public void Ticks()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) * 10) > 0)
}
[Fact]
public void TotalDays()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0)
}
[Fact]
public void TotalHours()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0)
}
[Fact]
public void TotalMilliseconds()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0)
}
[Fact]
public void TotalMinutes()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0)
}
[Fact]
public void TotalSeconds()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0)
}
[Fact]
public void Add()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0)
}
[Fact]
public void Subtract()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) - (1 * 86400000000)) > 0)
}
[Fact]
public void CompareTo()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0)
}
[Fact]
public void this_Equals()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000)))
}
[Fact]
public void this_ToString()
{
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') = 'ssss')
}
[Fact]
public void TimeSpan_Compare() {
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0)
}
[Fact]
public void TimeSpan_Equals() {
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000)))
}
[Fact]
public void TimeSpan_FromDays() {
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000)))
}
[Fact]
public void TimeSpan_FromHours() {
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000)))
}
[Fact]
public void TimeSpan_FromMilliseconds() {
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000)))
}
[Fact]
public void TimeSpan_FromMinutes() {
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000)))
}
[Fact]
public void TimeSpan_FromSeconds() {
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000000)))
}
[Fact]
public void TimeSpan_FromTicks() {
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 / 10)))
}
[Fact]
public void TimeSpan_Parse() {
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (cast(date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') as signed) > 0)
}
}
[Fact]
public void TimeSpan_Compare()
{
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0)
}
[Fact]
public void TimeSpan_Equals()
{
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000)))
}
[Fact]
public void TimeSpan_FromDays()
{
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000)))
}
[Fact]
public void TimeSpan_FromHours()
{
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000)))
}
[Fact]
public void TimeSpan_FromMilliseconds()
{
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000)))
}
[Fact]
public void TimeSpan_FromMinutes()
{
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000)))
}
[Fact]
public void TimeSpan_FromSeconds()
{
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000000)))
}
[Fact]
public void TimeSpan_FromTicks()
{
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 / 10)))
}
[Fact]
public void TimeSpan_Parse()
{
var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (cast(date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') as signed) > 0)
}
}
}

View File

@ -2,20 +2,24 @@ using FreeSql.DataAnnotations;
using System;
using Xunit;
namespace FreeSql.Tests.MySqlConnector {
public class MySqlDbFirstTest {
[Fact]
public void GetDatabases() {
namespace FreeSql.Tests.MySqlConnector
{
public class MySqlDbFirstTest
{
[Fact]
public void GetDatabases()
{
var t1 = g.mysql.DbFirst.GetDatabases();
var t1 = g.mysql.DbFirst.GetDatabases();
}
}
[Fact]
public void GetTablesByDatabase() {
[Fact]
public void GetTablesByDatabase()
{
var t2 = g.mysql.DbFirst.GetTablesByDatabase(g.mysql.DbFirst.GetDatabases()[0]);
var t2 = g.mysql.DbFirst.GetTablesByDatabase(g.mysql.DbFirst.GetDatabases()[0]);
}
}
}
}
}

View File

@ -4,19 +4,22 @@ using System.Diagnostics;
using System.Text;
public class g {
public class g
{
static Lazy<IFreeSql> mysqlLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd_mysqlconnector;Charset=utf8;SslMode=none;Max pool size=10")
.UseAutoSyncStructure(true)
.UseMonitorCommand(
cmd => {
Trace.WriteLine(cmd.CommandText);
}, //监听SQL命令对象在执行前
(cmd, traceLog) => {
Console.WriteLine(traceLog);
}) //监听SQL命令对象在执行后
.UseLazyLoading(true)
.Build());
public static IFreeSql mysql => mysqlLazy.Value;
static Lazy<IFreeSql> mysqlLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd_mysqlconnector;Charset=utf8;SslMode=none;Max pool size=10")
.UseAutoSyncStructure(true)
.UseMonitorCommand(
cmd =>
{
Trace.WriteLine(cmd.CommandText);
}, //监听SQL命令对象在执行前
(cmd, traceLog) =>
{
Console.WriteLine(traceLog);
}) //监听SQL命令对象在执行后
.UseLazyLoading(true)
.Build());
public static IFreeSql mysql => mysqlLazy.Value;
}

View File

@ -4,117 +4,134 @@ using System;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.DataAnnotations {
public class MySqlFluentTest {
namespace FreeSql.Tests.DataAnnotations
{
public class MySqlFluentTest
{
public MySqlFluentTest() {
}
public MySqlFluentTest()
{
}
[Fact]
public void DisableSyncStructure() {
Assert.Throws<MySqlException>(() => g.mysql.Select<ModelDisableSyncStructure>().ToList());
[Fact]
public void DisableSyncStructure()
{
Assert.Throws<MySqlException>(() => g.mysql.Select<ModelDisableSyncStructure>().ToList());
g.mysql.Select<ModelSyncStructure>().ToList();
}
[Table(DisableSyncStructure = true)]
class ModelDisableSyncStructure {
[Column(IsPrimary = false)]
public int pkid { get; set; }
}
class ModelSyncStructure {
[Column(IsPrimary = false)]
public int pkid { get; set; }
}
g.mysql.Select<ModelSyncStructure>().ToList();
}
[Table(DisableSyncStructure = true)]
class ModelDisableSyncStructure
{
[Column(IsPrimary = false)]
public int pkid { get; set; }
}
class ModelSyncStructure
{
[Column(IsPrimary = false)]
public int pkid { get; set; }
}
[Fact]
public void AopConfigEntity() {
g.mysql.CodeFirst.ConfigEntity<ModelAopConfigEntity>(a => a.Property(b => b.pkid).IsPrimary(true));
[Fact]
public void AopConfigEntity()
{
g.mysql.CodeFirst.ConfigEntity<ModelAopConfigEntity>(a => a.Property(b => b.pkid).IsPrimary(true));
g.mysql.Aop.ConfigEntity = (s, e) => {
var attr = e.EntityType.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.TableAttribute), false).FirstOrDefault() as System.ComponentModel.DataAnnotations.Schema.TableAttribute;
if (attr != null) {
e.ModifyResult.Name = attr.Name;
}
};
g.mysql.Aop.ConfigEntityProperty = (s, e) => {
if (e.Property.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.KeyAttribute), false).Any()) {
e.ModifyResult.IsPrimary = true;
}
};
g.mysql.Aop.ConfigEntity = (s, e) =>
{
var attr = e.EntityType.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.TableAttribute), false).FirstOrDefault() as System.ComponentModel.DataAnnotations.Schema.TableAttribute;
if (attr != null)
{
e.ModifyResult.Name = attr.Name;
}
};
g.mysql.Aop.ConfigEntityProperty = (s, e) =>
{
if (e.Property.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.KeyAttribute), false).Any())
{
e.ModifyResult.IsPrimary = true;
}
};
var tsql1 = g.mysql.Select<ModelAopConfigEntity>().WhereDynamic(1).ToSql();
}
[System.ComponentModel.DataAnnotations.Schema.Table("xxx")]
class ModelAopConfigEntity {
[System.ComponentModel.DataAnnotations.Key]
[Column(IsPrimary = false)]
public int pkid { get; set; }
}
var tsql1 = g.mysql.Select<ModelAopConfigEntity>().WhereDynamic(1).ToSql();
}
[System.ComponentModel.DataAnnotations.Schema.Table("xxx")]
class ModelAopConfigEntity
{
[System.ComponentModel.DataAnnotations.Key]
[Column(IsPrimary = false)]
public int pkid { get; set; }
}
[Fact]
public void Fluent() {
g.mysql.CodeFirst
//.ConfigEntity<TestFluenttb1>(a => {
// a.Name("xxdkdkdk1").SelectFilter("a.Id22 > 0");
// a.Property(b => b.Id).Name("Id22").IsIdentity(true);
// a.Property(b => b.name).DbType("varchar(100)").IsNullable(true);
//})
[Fact]
public void Fluent()
{
g.mysql.CodeFirst
//.ConfigEntity<TestFluenttb1>(a => {
// a.Name("xxdkdkdk1").SelectFilter("a.Id22 > 0");
// a.Property(b => b.Id).Name("Id22").IsIdentity(true);
// a.Property(b => b.name).DbType("varchar(100)").IsNullable(true);
//})
.ConfigEntity(typeof(TestFluenttb1), a => {
a.Name("xxdkdkdk1222").SelectFilter("a.Id22dd > 1");
a.Property("Id").Name("Id22dd").IsIdentity(true);
a.Property("Name").DbType("varchar(101)").IsNullable(true);
})
.ConfigEntity(typeof(TestFluenttb1), a =>
{
a.Name("xxdkdkdk1222").SelectFilter("a.Id22dd > 1");
a.Property("Id").Name("Id22dd").IsIdentity(true);
a.Property("Name").DbType("varchar(101)").IsNullable(true);
})
.ConfigEntity<TestFluenttb2>(a => {
a.Name("xxdkdkdk2").SelectFilter("a.Idx > 0");
a.Property(b => b.Id).Name("Id22").IsIdentity(true);
a.Property(b => b.name).DbType("varchar(100)").IsNullable(true);
})
;
.ConfigEntity<TestFluenttb2>(a =>
{
a.Name("xxdkdkdk2").SelectFilter("a.Idx > 0");
a.Property(b => b.Id).Name("Id22").IsIdentity(true);
a.Property(b => b.name).DbType("varchar(100)").IsNullable(true);
})
;
var ddl1 = g.mysql.CodeFirst.GetComparisonDDLStatements<TestFluenttb1>();
var ddl2 = g.mysql.CodeFirst.GetComparisonDDLStatements<TestFluenttb2>();
var ddl1 = g.mysql.CodeFirst.GetComparisonDDLStatements<TestFluenttb1>();
var ddl2 = g.mysql.CodeFirst.GetComparisonDDLStatements<TestFluenttb2>();
var t1id = g.mysql.Insert<TestFluenttb1>().AppendData(new TestFluenttb1 { }).ExecuteIdentity();
var t1 = g.mysql.Select<TestFluenttb1>(t1id).ToOne();
var t1id = g.mysql.Insert<TestFluenttb1>().AppendData(new TestFluenttb1 { }).ExecuteIdentity();
var t1 = g.mysql.Select<TestFluenttb1>(t1id).ToOne();
var t2lastId = g.mysql.Select<TestFluenttb2>().Max(a => a.Id);
var t2affrows = g.mysql.Insert<TestFluenttb2>().AppendData(new TestFluenttb2 { Id = t2lastId + 1 }).ExecuteAffrows();
var t2 = g.mysql.Select<TestFluenttb2>(t2lastId + 1).ToOne();
}
var t2lastId = g.mysql.Select<TestFluenttb2>().Max(a => a.Id);
var t2affrows = g.mysql.Insert<TestFluenttb2>().AppendData(new TestFluenttb2 { Id = t2lastId + 1 }).ExecuteAffrows();
var t2 = g.mysql.Select<TestFluenttb2>(t2lastId + 1).ToOne();
}
class TestFluenttb1
{
public int Id { get; set; }
class TestFluenttb1
{
public int Id { get; set; }
public string name { get; set; } = "defaultValue";
}
public string name { get; set; } = "defaultValue";
}
[Table(Name = "cccccdddwww")]
class TestFluenttb2
{
[Column(Name = "Idx", IsPrimary = true, IsIdentity = false)]
public int Id { get; set; }
[Table(Name = "cccccdddwww")]
class TestFluenttb2
{
[Column(Name = "Idx", IsPrimary = true, IsIdentity = false)]
public int Id { get; set; }
public string name { get; set; } = "defaultValue";
}
public string name { get; set; } = "defaultValue";
}
[Fact]
public void IsIgnore() {
var item = new TestIsIgnore { };
Assert.Equal(1, g.mysql.Insert<TestIsIgnore>().AppendData(item).ExecuteAffrows());
[Fact]
public void IsIgnore()
{
var item = new TestIsIgnore { };
Assert.Equal(1, g.mysql.Insert<TestIsIgnore>().AppendData(item).ExecuteAffrows());
var find = g.mysql.Select<TestIsIgnore>().Where(a => a.id == item.id).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
}
var find = g.mysql.Select<TestIsIgnore>().Where(a => a.id == item.id).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
}
class TestIsIgnore {
public Guid id { get; set; }
class TestIsIgnore
{
public Guid id { get; set; }
[Column(IsIgnore = true)]
public bool isignore { get; set; }
}
}
[Column(IsIgnore = true)]
public bool isignore { get; set; }
}
}
}

View File

@ -4,118 +4,130 @@ using System;
using System.Data.SqlClient;
using Xunit;
namespace FreeSql.Tests.DataAnnotations {
[Collection("SqlServerCollection")]
public class SqlServerFluentTest {
namespace FreeSql.Tests.DataAnnotations
{
[Collection("SqlServerCollection")]
public class SqlServerFluentTest
{
SqlServerFixture _sqlserverFixture;
SqlServerFixture _sqlserverFixture;
public SqlServerFluentTest(SqlServerFixture sqlserverFixture)
{
_sqlserverFixture = sqlserverFixture;
}
public SqlServerFluentTest(SqlServerFixture sqlserverFixture)
{
_sqlserverFixture = sqlserverFixture;
}
[Fact]
public void DisableSyncStructure() {
Assert.Throws<SqlException>(() => _sqlserverFixture.SqlServer.Select<ModelDisableSyncStructure>().ToList());
[Fact]
public void DisableSyncStructure()
{
Assert.Throws<SqlException>(() => _sqlserverFixture.SqlServer.Select<ModelDisableSyncStructure>().ToList());
_sqlserverFixture.SqlServer.Select<ModelSyncStructure>().ToList();
}
[Table(DisableSyncStructure = true)]
class ModelDisableSyncStructure {
[Column(IsPrimary = false)]
public int pkid { get; set; }
}
class ModelSyncStructure {
[Column(IsPrimary = false)]
public int pkid { get; set; }
}
_sqlserverFixture.SqlServer.Select<ModelSyncStructure>().ToList();
}
[Table(DisableSyncStructure = true)]
class ModelDisableSyncStructure
{
[Column(IsPrimary = false)]
public int pkid { get; set; }
}
class ModelSyncStructure
{
[Column(IsPrimary = false)]
public int pkid { get; set; }
}
[Fact]
public void Fluent() {
_sqlserverFixture.SqlServer.CodeFirst
//.ConfigEntity<TestFluenttb1>(a => {
// a.Name("xxdkdkdk1").SelectFilter("a.Id22 > 0");
// a.Property(b => b.Id).Name("Id22").IsIdentity(true);
// a.Property(b => b.name).DbType("varchar(100)").IsNullable(true);
//})
[Fact]
public void Fluent()
{
_sqlserverFixture.SqlServer.CodeFirst
//.ConfigEntity<TestFluenttb1>(a => {
// a.Name("xxdkdkdk1").SelectFilter("a.Id22 > 0");
// a.Property(b => b.Id).Name("Id22").IsIdentity(true);
// a.Property(b => b.name).DbType("varchar(100)").IsNullable(true);
//})
.ConfigEntity(typeof(TestFluenttb1), a => {
a.Name("xxdkdkdk1222").SelectFilter("a.Id22dd > 1");
a.Property("Id").Name("Id22dd").IsIdentity(true);
a.Property("Name").DbType("varchar(101)").IsNullable(true);
})
.ConfigEntity(typeof(TestFluenttb1), a =>
{
a.Name("xxdkdkdk1222").SelectFilter("a.Id22dd > 1");
a.Property("Id").Name("Id22dd").IsIdentity(true);
a.Property("Name").DbType("varchar(101)").IsNullable(true);
})
.ConfigEntity<TestFluenttb2>(a => {
a.Name("xxdkdkdk2").SelectFilter("a.Idx > 0");
a.Property(b => b.Id).Name("Id22").IsIdentity(true);
a.Property(b => b.name).DbType("varchar(100)").IsNullable(true);
})
;
.ConfigEntity<TestFluenttb2>(a =>
{
a.Name("xxdkdkdk2").SelectFilter("a.Idx > 0");
a.Property(b => b.Id).Name("Id22").IsIdentity(true);
a.Property(b => b.name).DbType("varchar(100)").IsNullable(true);
})
;
var ddl1 = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements<TestFluenttb1>();
var ddl2 = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements<TestFluenttb2>();
var ddl1 = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements<TestFluenttb1>();
var ddl2 = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements<TestFluenttb2>();
var t1id = _sqlserverFixture.SqlServer.Insert<TestFluenttb1>().AppendData(new TestFluenttb1 { }).ExecuteIdentity();
var t1 = _sqlserverFixture.SqlServer.Select<TestFluenttb1>(t1id).ToOne();
var t1id = _sqlserverFixture.SqlServer.Insert<TestFluenttb1>().AppendData(new TestFluenttb1 { }).ExecuteIdentity();
var t1 = _sqlserverFixture.SqlServer.Select<TestFluenttb1>(t1id).ToOne();
var t2lastId = _sqlserverFixture.SqlServer.Select<TestFluenttb2>().Max(a => a.Id);
var t2affrows = _sqlserverFixture.SqlServer.Insert<TestFluenttb2>().AppendData(new TestFluenttb2 { Id = t2lastId + 1 }).ExecuteAffrows();
var t2 = _sqlserverFixture.SqlServer.Select<TestFluenttb2>(t2lastId + 1).ToOne();
}
var t2lastId = _sqlserverFixture.SqlServer.Select<TestFluenttb2>().Max(a => a.Id);
var t2affrows = _sqlserverFixture.SqlServer.Insert<TestFluenttb2>().AppendData(new TestFluenttb2 { Id = t2lastId + 1 }).ExecuteAffrows();
var t2 = _sqlserverFixture.SqlServer.Select<TestFluenttb2>(t2lastId + 1).ToOne();
}
[Fact]
public void GroupPrimaryKey() {
_sqlserverFixture.SqlServer.CodeFirst.SyncStructure<TestgroupkeyTb>();
g.mysql.CodeFirst.SyncStructure<TestgroupkeyTb>();
g.pgsql.CodeFirst.SyncStructure<TestgroupkeyTb>();
g.sqlite.CodeFirst.SyncStructure<TestgroupkeyTb>();
g.oracle.CodeFirst.SyncStructure<TestgroupkeyTb>();
}
[Fact]
public void GroupPrimaryKey()
{
_sqlserverFixture.SqlServer.CodeFirst.SyncStructure<TestgroupkeyTb>();
g.mysql.CodeFirst.SyncStructure<TestgroupkeyTb>();
g.pgsql.CodeFirst.SyncStructure<TestgroupkeyTb>();
g.sqlite.CodeFirst.SyncStructure<TestgroupkeyTb>();
g.oracle.CodeFirst.SyncStructure<TestgroupkeyTb>();
}
class TestFluenttb1
{
public int Id { get; set; }
class TestFluenttb1
{
public int Id { get; set; }
public string name { get; set; } = "defaultValue";
}
public string name { get; set; } = "defaultValue";
}
[Table(Name = "cccccdddwww")]
class TestFluenttb2
{
[Column(Name = "Idx", IsPrimary = true, IsIdentity = false)]
public int Id { get; set; }
[Table(Name = "cccccdddwww")]
class TestFluenttb2
{
[Column(Name = "Idx", IsPrimary = true, IsIdentity = false)]
public int Id { get; set; }
public string name { get; set; } = "defaultValue";
}
public string name { get; set; } = "defaultValue";
}
[Table(Name = "test_groupkey")]
class TestgroupkeyTb {
[Column(IsPrimary = true)]
public int Id { get; set; }
[Column(IsPrimary = true)]
public int id2 { get; set; }
[Table(Name = "test_groupkey")]
class TestgroupkeyTb
{
[Column(IsPrimary = true)]
public int Id { get; set; }
[Column(IsPrimary = true)]
public int id2 { get; set; }
public string name { get; set; } = "defaultValue";
}
public string name { get; set; } = "defaultValue";
}
[Fact]
public void IsIgnore() {
var item = new TestIsIgnore { };
Assert.Equal(1, _sqlserverFixture.SqlServer.Insert<TestIsIgnore>().AppendData(item).ExecuteAffrows());
[Fact]
public void IsIgnore()
{
var item = new TestIsIgnore { };
Assert.Equal(1, _sqlserverFixture.SqlServer.Insert<TestIsIgnore>().AppendData(item).ExecuteAffrows());
var find = _sqlserverFixture.SqlServer.Select<TestIsIgnore>().Where(a => a.id == item.id).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
}
var find = _sqlserverFixture.SqlServer.Select<TestIsIgnore>().Where(a => a.id == item.id).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
}
class TestIsIgnore {
public Guid id { get; set; }
class TestIsIgnore
{
public Guid id { get; set; }
[Column(IsIgnore = true)]
public bool isignore { get; set; }
}
}
[Column(IsIgnore = true)]
public bool isignore { get; set; }
}
}
}

View File

@ -5,11 +5,11 @@ using Xunit;
namespace FreeSql.Tests.DataContext.SqlServer
{
[CollectionDefinition("SqlServerCollection")]
public class SqlServerCollection : ICollectionFixture<SqlServerFixture>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
}
[CollectionDefinition("SqlServerCollection")]
public class SqlServerCollection : ICollectionFixture<SqlServerFixture>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
}
}

View File

@ -6,56 +6,56 @@ using System.Text;
namespace FreeSql.Tests.DataContext.SqlServer
{
public class SqlServerFixture : IDisposable
{
public SqlServerFixture()
{
sqlServerLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=(localdb)\\mssqllocaldb;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
.UseMonitorCommand(t => Trace.WriteLine(t.CommandText))
.Build());
public class SqlServerFixture : IDisposable
{
public SqlServerFixture()
{
sqlServerLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=(localdb)\\mssqllocaldb;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
.UseMonitorCommand(t => Trace.WriteLine(t.CommandText))
.Build());
// ... initialize data in the test database ...
}
// ... initialize data in the test database ...
}
public void Dispose()
{
// ... clean up test data from the database ...
ClearDataBase();
}
public void Dispose()
{
// ... clean up test data from the database ...
ClearDataBase();
}
private void ClearDataBase()
{
var dataTables = SqlServer.DbFirst.GetTablesByDatabase();
if (dataTables.Any(item => item.Name == "TopicAddField" && item.Schema == "dbo2"))
{
SqlServer.Ado.ExecuteNonQuery("TRUNCATE TABLE dbo2.TopicAddField ");
SqlServer.Ado.ExecuteNonQuery("DROP TABLE dbo2.TopicAddField");
SqlServer.Ado.ExecuteNonQuery("DROP SCHEMA dbo2");
}
private void ClearDataBase()
{
var dataTables = SqlServer.DbFirst.GetTablesByDatabase();
if (dataTables.Any(item => item.Name == "TopicAddField" && item.Schema == "dbo2"))
{
SqlServer.Ado.ExecuteNonQuery("TRUNCATE TABLE dbo2.TopicAddField ");
SqlServer.Ado.ExecuteNonQuery("DROP TABLE dbo2.TopicAddField");
SqlServer.Ado.ExecuteNonQuery("DROP SCHEMA dbo2");
}
var tempTables = new string[] { "cccccdddwww", "song", "tag", "Song_tag", "tb_alltype", "tb_topic", "tb_topic22",
"tb_topic22211", "tb_topic111333", "TestTypeInfo", "TestTypeInfo333", "TestTypeParentInfo",
"TestTypeParentInfo23123", "xxdkdkdk1222", "xxx"};
foreach (var tempTable in tempTables)
{
DeleteTmpTable(dataTables, tempTable);
}
}
var tempTables = new string[] { "cccccdddwww", "song", "tag", "Song_tag", "tb_alltype", "tb_topic", "tb_topic22",
"tb_topic22211", "tb_topic111333", "TestTypeInfo", "TestTypeInfo333", "TestTypeParentInfo",
"TestTypeParentInfo23123", "xxdkdkdk1222", "xxx"};
foreach (var tempTable in tempTables)
{
DeleteTmpTable(dataTables, tempTable);
}
}
private void DeleteTmpTable(List<DatabaseModel.DbTableInfo> dbTables, string deleteTableName, string schemaName = "dbo")
{
if (dbTables.Any(item => item.Name.ToLower() == deleteTableName.ToLower() && item.Schema.ToLower() == schemaName.ToLower()))
{
SqlServer.Ado.ExecuteNonQuery($"TRUNCATE TABLE {schemaName.ToLower()}.{deleteTableName}");
SqlServer.Ado.ExecuteNonQuery($"DROP TABLE {schemaName.ToLower()}.{deleteTableName}");
}
}
private void DeleteTmpTable(List<DatabaseModel.DbTableInfo> dbTables, string deleteTableName, string schemaName = "dbo")
{
if (dbTables.Any(item => item.Name.ToLower() == deleteTableName.ToLower() && item.Schema.ToLower() == schemaName.ToLower()))
{
SqlServer.Ado.ExecuteNonQuery($"TRUNCATE TABLE {schemaName.ToLower()}.{deleteTableName}");
SqlServer.Ado.ExecuteNonQuery($"DROP TABLE {schemaName.ToLower()}.{deleteTableName}");
}
}
private Lazy<IFreeSql> sqlServerLazy;
public IFreeSql SqlServer => sqlServerLazy.Value;
}
private Lazy<IFreeSql> sqlServerLazy;
public IFreeSql SqlServer => sqlServerLazy.Value;
}
}

View File

@ -10,423 +10,440 @@ using Npgsql.LegacyPostgis;
using FreeSql.Internal;
using System.Linq.Expressions;
namespace FreeSql.ExpressionTree {
public class GetDataReaderValueBlockExpressionTest {
namespace FreeSql.ExpressionTree
{
public class GetDataReaderValueBlockExpressionTest
{
[Fact]
public void Guid2() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(Guid.Empty));
Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), Guid.Empty));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(Guid.NewGuid()));
var newguid = Guid.NewGuid();
Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid), newguid));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(null));
Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), null));
[Fact]
public void Guid2()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(Guid.Empty));
Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), Guid.Empty));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(Guid.NewGuid()));
var newguid = Guid.NewGuid();
Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid), newguid));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(null));
Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), null));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(Guid.Empty));
Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid?), Guid.Empty));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(newguid));
Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid?), newguid));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(Guid?), null));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(Guid.Empty));
Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid?), Guid.Empty));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(newguid));
Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid?), newguid));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(Guid?), null));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(Guid.Empty.ToString()));
Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), Guid.Empty.ToString()));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(newguid.ToString()));
Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid), newguid.ToString()));
var exp333 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant("-1"));
Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), "-1"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(Guid.Empty.ToString()));
Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), Guid.Empty.ToString()));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(newguid.ToString()));
Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid), newguid.ToString()));
var exp333 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant("-1"));
Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), "-1"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(Guid.Empty.ToString()));
Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid?), Guid.Empty.ToString()));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(newguid.ToString()));
Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid?), newguid.ToString()));
var exp3333 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant("-1"));
Assert.Null(Utils.GetDataReaderValue(typeof(Guid?), "-1"));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(Guid.Empty.ToString()));
Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid?), Guid.Empty.ToString()));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(newguid.ToString()));
Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid?), newguid.ToString()));
var exp3333 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant("-1"));
Assert.Null(Utils.GetDataReaderValue(typeof(Guid?), "-1"));
}
[Fact]
public void Boolean() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant(true));
Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool), true));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant(false));
Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool), false));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant(null));
Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool), null));
[Fact]
public void Boolean()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant(true));
Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool), true));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant(false));
Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool), false));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant(null));
Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool), null));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(bool?), Expression.Constant(true));
Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool?), true));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(bool?), Expression.Constant(false));
Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool?), false));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(bool?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(bool?), null));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(bool?), Expression.Constant(true));
Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool?), true));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(bool?), Expression.Constant(false));
Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool?), false));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(bool?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(bool?), null));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("1"));
Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool), true));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("0"));
Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool), false));
var exp333 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("-1"));
Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool), true));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("1"));
Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool), true));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("0"));
Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool), false));
var exp333 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("-1"));
Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool), true));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("true"));
Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool?), true));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("True"));
Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool?), true));
var exp3333 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("false"));
Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool?), false));
var exp4444 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("False"));
Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool?), false));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("true"));
Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool?), true));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("True"));
Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool?), true));
var exp3333 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("false"));
Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool?), false));
var exp4444 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("False"));
Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool?), false));
}
[Fact]
public void SByte() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant(sbyte.MinValue));
Assert.Equal(sbyte.MinValue, Utils.GetDataReaderValue(typeof(sbyte), sbyte.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant(sbyte.MaxValue));
Assert.Equal(sbyte.MaxValue, Utils.GetDataReaderValue(typeof(sbyte), sbyte.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant("127"));
Assert.Equal((sbyte)127, Utils.GetDataReaderValue(typeof(sbyte), "127"));
[Fact]
public void SByte()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant(sbyte.MinValue));
Assert.Equal(sbyte.MinValue, Utils.GetDataReaderValue(typeof(sbyte), sbyte.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant(sbyte.MaxValue));
Assert.Equal(sbyte.MaxValue, Utils.GetDataReaderValue(typeof(sbyte), sbyte.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant("127"));
Assert.Equal((sbyte)127, Utils.GetDataReaderValue(typeof(sbyte), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant(sbyte.MinValue));
Assert.Equal(sbyte.MinValue, Utils.GetDataReaderValue(typeof(sbyte?), sbyte.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant(sbyte.MaxValue));
Assert.Equal(sbyte.MaxValue, Utils.GetDataReaderValue(typeof(sbyte?), sbyte.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant("127"));
Assert.Equal((sbyte)127, Utils.GetDataReaderValue(typeof(sbyte?), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant(sbyte.MinValue));
Assert.Equal(sbyte.MinValue, Utils.GetDataReaderValue(typeof(sbyte?), sbyte.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant(sbyte.MaxValue));
Assert.Equal(sbyte.MaxValue, Utils.GetDataReaderValue(typeof(sbyte?), sbyte.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant("127"));
Assert.Equal((sbyte)127, Utils.GetDataReaderValue(typeof(sbyte?), "127"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant(null));
Assert.Equal(default(sbyte), Utils.GetDataReaderValue(typeof(sbyte), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant("aaa"));
Assert.Equal(default(sbyte), Utils.GetDataReaderValue(typeof(sbyte), "aaa"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant(null));
Assert.Equal(default(sbyte), Utils.GetDataReaderValue(typeof(sbyte), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant("aaa"));
Assert.Equal(default(sbyte), Utils.GetDataReaderValue(typeof(sbyte), "aaa"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(sbyte?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(sbyte?), "aaa"));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(sbyte?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(sbyte?), "aaa"));
}
[Fact]
public void Short() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant(short.MinValue));
Assert.Equal(short.MinValue, Utils.GetDataReaderValue(typeof(short), short.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant(short.MaxValue));
Assert.Equal(short.MaxValue, Utils.GetDataReaderValue(typeof(short), short.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant("127"));
Assert.Equal((short)127, Utils.GetDataReaderValue(typeof(short), "127"));
[Fact]
public void Short()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant(short.MinValue));
Assert.Equal(short.MinValue, Utils.GetDataReaderValue(typeof(short), short.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant(short.MaxValue));
Assert.Equal(short.MaxValue, Utils.GetDataReaderValue(typeof(short), short.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant("127"));
Assert.Equal((short)127, Utils.GetDataReaderValue(typeof(short), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant(short.MinValue));
Assert.Equal(short.MinValue, Utils.GetDataReaderValue(typeof(short?), short.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant(short.MaxValue));
Assert.Equal(short.MaxValue, Utils.GetDataReaderValue(typeof(short?), short.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant("127"));
Assert.Equal((short)127, Utils.GetDataReaderValue(typeof(short?), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant(short.MinValue));
Assert.Equal(short.MinValue, Utils.GetDataReaderValue(typeof(short?), short.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant(short.MaxValue));
Assert.Equal(short.MaxValue, Utils.GetDataReaderValue(typeof(short?), short.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant("127"));
Assert.Equal((short)127, Utils.GetDataReaderValue(typeof(short?), "127"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant(null));
Assert.Equal(default(short), Utils.GetDataReaderValue(typeof(short), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant("aaa"));
Assert.Equal(default(short), Utils.GetDataReaderValue(typeof(short), "aaa"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant(null));
Assert.Equal(default(short), Utils.GetDataReaderValue(typeof(short), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant("aaa"));
Assert.Equal(default(short), Utils.GetDataReaderValue(typeof(short), "aaa"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(short?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(short?), "aaa"));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(short?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(short?), "aaa"));
}
[Fact]
public void Int() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant(int.MinValue));
Assert.Equal(int.MinValue, Utils.GetDataReaderValue(typeof(int), int.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant(int.MaxValue));
Assert.Equal(int.MaxValue, Utils.GetDataReaderValue(typeof(int), int.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant("127"));
Assert.Equal((int)127, Utils.GetDataReaderValue(typeof(int), "127"));
[Fact]
public void Int()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant(int.MinValue));
Assert.Equal(int.MinValue, Utils.GetDataReaderValue(typeof(int), int.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant(int.MaxValue));
Assert.Equal(int.MaxValue, Utils.GetDataReaderValue(typeof(int), int.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant("127"));
Assert.Equal((int)127, Utils.GetDataReaderValue(typeof(int), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant(int.MinValue));
Assert.Equal(int.MinValue, Utils.GetDataReaderValue(typeof(int?), int.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant(int.MaxValue));
Assert.Equal(int.MaxValue, Utils.GetDataReaderValue(typeof(int?), int.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant("127"));
Assert.Equal((int)127, Utils.GetDataReaderValue(typeof(int?), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant(int.MinValue));
Assert.Equal(int.MinValue, Utils.GetDataReaderValue(typeof(int?), int.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant(int.MaxValue));
Assert.Equal(int.MaxValue, Utils.GetDataReaderValue(typeof(int?), int.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant("127"));
Assert.Equal((int)127, Utils.GetDataReaderValue(typeof(int?), "127"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant(null));
Assert.Equal(default(int), Utils.GetDataReaderValue(typeof(int), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant("aaa"));
Assert.Equal(default(int), Utils.GetDataReaderValue(typeof(int), "aaa"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant(null));
Assert.Equal(default(int), Utils.GetDataReaderValue(typeof(int), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant("aaa"));
Assert.Equal(default(int), Utils.GetDataReaderValue(typeof(int), "aaa"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(int?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(int?), "aaa"));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(int?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(int?), "aaa"));
}
[Fact]
public void Long() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant(long.MinValue));
Assert.Equal(long.MinValue, Utils.GetDataReaderValue(typeof(long), long.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant(long.MaxValue));
Assert.Equal(long.MaxValue, Utils.GetDataReaderValue(typeof(long), long.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant("127"));
Assert.Equal((long)127, Utils.GetDataReaderValue(typeof(long), "127"));
[Fact]
public void Long()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant(long.MinValue));
Assert.Equal(long.MinValue, Utils.GetDataReaderValue(typeof(long), long.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant(long.MaxValue));
Assert.Equal(long.MaxValue, Utils.GetDataReaderValue(typeof(long), long.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant("127"));
Assert.Equal((long)127, Utils.GetDataReaderValue(typeof(long), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant(long.MinValue));
Assert.Equal(long.MinValue, Utils.GetDataReaderValue(typeof(long?), long.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant(long.MaxValue));
Assert.Equal(long.MaxValue, Utils.GetDataReaderValue(typeof(long?), long.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant("127"));
Assert.Equal((long)127, Utils.GetDataReaderValue(typeof(long?), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant(long.MinValue));
Assert.Equal(long.MinValue, Utils.GetDataReaderValue(typeof(long?), long.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant(long.MaxValue));
Assert.Equal(long.MaxValue, Utils.GetDataReaderValue(typeof(long?), long.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant("127"));
Assert.Equal((long)127, Utils.GetDataReaderValue(typeof(long?), "127"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant(null));
Assert.Equal(default(long), Utils.GetDataReaderValue(typeof(long), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant("aaa"));
Assert.Equal(default(long), Utils.GetDataReaderValue(typeof(long), "aaa"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant(null));
Assert.Equal(default(long), Utils.GetDataReaderValue(typeof(long), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant("aaa"));
Assert.Equal(default(long), Utils.GetDataReaderValue(typeof(long), "aaa"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(long?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(long?), "aaa"));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(long?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(long?), "aaa"));
}
[Fact]
public void Byte() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant(byte.MinValue));
Assert.Equal(byte.MinValue, Utils.GetDataReaderValue(typeof(byte), byte.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant(byte.MaxValue));
Assert.Equal(byte.MaxValue, Utils.GetDataReaderValue(typeof(byte), byte.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant("127"));
Assert.Equal((byte)127, Utils.GetDataReaderValue(typeof(byte), "127"));
[Fact]
public void Byte()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant(byte.MinValue));
Assert.Equal(byte.MinValue, Utils.GetDataReaderValue(typeof(byte), byte.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant(byte.MaxValue));
Assert.Equal(byte.MaxValue, Utils.GetDataReaderValue(typeof(byte), byte.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant("127"));
Assert.Equal((byte)127, Utils.GetDataReaderValue(typeof(byte), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant(byte.MinValue));
Assert.Equal(byte.MinValue, Utils.GetDataReaderValue(typeof(byte?), byte.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant(byte.MaxValue));
Assert.Equal(byte.MaxValue, Utils.GetDataReaderValue(typeof(byte?), byte.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant("127"));
Assert.Equal((byte)127, Utils.GetDataReaderValue(typeof(byte?), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant(byte.MinValue));
Assert.Equal(byte.MinValue, Utils.GetDataReaderValue(typeof(byte?), byte.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant(byte.MaxValue));
Assert.Equal(byte.MaxValue, Utils.GetDataReaderValue(typeof(byte?), byte.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant("127"));
Assert.Equal((byte)127, Utils.GetDataReaderValue(typeof(byte?), "127"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant(null));
Assert.Equal(default(byte), Utils.GetDataReaderValue(typeof(byte), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant("aaa"));
Assert.Equal(default(byte), Utils.GetDataReaderValue(typeof(byte), "aaa"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant(null));
Assert.Equal(default(byte), Utils.GetDataReaderValue(typeof(byte), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant("aaa"));
Assert.Equal(default(byte), Utils.GetDataReaderValue(typeof(byte), "aaa"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(byte?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(byte?), "aaa"));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(byte?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(byte?), "aaa"));
}
[Fact]
public void UShort() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant(ushort.MinValue));
Assert.Equal(ushort.MinValue, Utils.GetDataReaderValue(typeof(ushort), ushort.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant(ushort.MaxValue));
Assert.Equal(ushort.MaxValue, Utils.GetDataReaderValue(typeof(ushort), ushort.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant("127"));
Assert.Equal((ushort)127, Utils.GetDataReaderValue(typeof(ushort), "127"));
[Fact]
public void UShort()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant(ushort.MinValue));
Assert.Equal(ushort.MinValue, Utils.GetDataReaderValue(typeof(ushort), ushort.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant(ushort.MaxValue));
Assert.Equal(ushort.MaxValue, Utils.GetDataReaderValue(typeof(ushort), ushort.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant("127"));
Assert.Equal((ushort)127, Utils.GetDataReaderValue(typeof(ushort), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant(ushort.MinValue));
Assert.Equal(ushort.MinValue, Utils.GetDataReaderValue(typeof(ushort?), ushort.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant(ushort.MaxValue));
Assert.Equal(ushort.MaxValue, Utils.GetDataReaderValue(typeof(ushort?), ushort.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant("127"));
Assert.Equal((ushort)127, Utils.GetDataReaderValue(typeof(ushort?), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant(ushort.MinValue));
Assert.Equal(ushort.MinValue, Utils.GetDataReaderValue(typeof(ushort?), ushort.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant(ushort.MaxValue));
Assert.Equal(ushort.MaxValue, Utils.GetDataReaderValue(typeof(ushort?), ushort.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant("127"));
Assert.Equal((ushort)127, Utils.GetDataReaderValue(typeof(ushort?), "127"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant(null));
Assert.Equal(default(ushort), Utils.GetDataReaderValue(typeof(ushort), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant("aaa"));
Assert.Equal(default(ushort), Utils.GetDataReaderValue(typeof(ushort), "aaa"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant(null));
Assert.Equal(default(ushort), Utils.GetDataReaderValue(typeof(ushort), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant("aaa"));
Assert.Equal(default(ushort), Utils.GetDataReaderValue(typeof(ushort), "aaa"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(ushort?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(ushort?), "aaa"));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(ushort?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(ushort?), "aaa"));
}
[Fact]
public void UInt() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant(uint.MinValue));
Assert.Equal(uint.MinValue, Utils.GetDataReaderValue(typeof(uint), uint.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant(uint.MaxValue));
Assert.Equal(uint.MaxValue, Utils.GetDataReaderValue(typeof(uint), uint.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant("127"));
Assert.Equal((uint)127, Utils.GetDataReaderValue(typeof(uint), "127"));
[Fact]
public void UInt()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant(uint.MinValue));
Assert.Equal(uint.MinValue, Utils.GetDataReaderValue(typeof(uint), uint.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant(uint.MaxValue));
Assert.Equal(uint.MaxValue, Utils.GetDataReaderValue(typeof(uint), uint.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant("127"));
Assert.Equal((uint)127, Utils.GetDataReaderValue(typeof(uint), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant(uint.MinValue));
Assert.Equal(uint.MinValue, Utils.GetDataReaderValue(typeof(uint?), uint.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant(uint.MaxValue));
Assert.Equal(uint.MaxValue, Utils.GetDataReaderValue(typeof(uint?), uint.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant("127"));
Assert.Equal((uint)127, Utils.GetDataReaderValue(typeof(uint?), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant(uint.MinValue));
Assert.Equal(uint.MinValue, Utils.GetDataReaderValue(typeof(uint?), uint.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant(uint.MaxValue));
Assert.Equal(uint.MaxValue, Utils.GetDataReaderValue(typeof(uint?), uint.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant("127"));
Assert.Equal((uint)127, Utils.GetDataReaderValue(typeof(uint?), "127"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant(null));
Assert.Equal(default(uint), Utils.GetDataReaderValue(typeof(uint), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant("aaa"));
Assert.Equal(default(uint), Utils.GetDataReaderValue(typeof(uint), "aaa"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant(null));
Assert.Equal(default(uint), Utils.GetDataReaderValue(typeof(uint), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant("aaa"));
Assert.Equal(default(uint), Utils.GetDataReaderValue(typeof(uint), "aaa"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(uint?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(uint?), "aaa"));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(uint?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(uint?), "aaa"));
}
[Fact]
public void ULong() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant(ulong.MinValue));
Assert.Equal(ulong.MinValue, Utils.GetDataReaderValue(typeof(ulong), ulong.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant(ulong.MaxValue));
Assert.Equal(ulong.MaxValue, Utils.GetDataReaderValue(typeof(ulong), ulong.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant("127"));
Assert.Equal((ulong)127, Utils.GetDataReaderValue(typeof(ulong), "127"));
[Fact]
public void ULong()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant(ulong.MinValue));
Assert.Equal(ulong.MinValue, Utils.GetDataReaderValue(typeof(ulong), ulong.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant(ulong.MaxValue));
Assert.Equal(ulong.MaxValue, Utils.GetDataReaderValue(typeof(ulong), ulong.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant("127"));
Assert.Equal((ulong)127, Utils.GetDataReaderValue(typeof(ulong), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant(ulong.MinValue));
Assert.Equal(ulong.MinValue, Utils.GetDataReaderValue(typeof(ulong?), ulong.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant(ulong.MaxValue));
Assert.Equal(ulong.MaxValue, Utils.GetDataReaderValue(typeof(ulong?), ulong.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant("127"));
Assert.Equal((ulong)127, Utils.GetDataReaderValue(typeof(ulong?), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant(ulong.MinValue));
Assert.Equal(ulong.MinValue, Utils.GetDataReaderValue(typeof(ulong?), ulong.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant(ulong.MaxValue));
Assert.Equal(ulong.MaxValue, Utils.GetDataReaderValue(typeof(ulong?), ulong.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant("127"));
Assert.Equal((ulong)127, Utils.GetDataReaderValue(typeof(ulong?), "127"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant(null));
Assert.Equal(default(ulong), Utils.GetDataReaderValue(typeof(ulong), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant("aaa"));
Assert.Equal(default(ulong), Utils.GetDataReaderValue(typeof(ulong), "aaa"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant(null));
Assert.Equal(default(ulong), Utils.GetDataReaderValue(typeof(ulong), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant("aaa"));
Assert.Equal(default(ulong), Utils.GetDataReaderValue(typeof(ulong), "aaa"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(ulong?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(ulong?), "aaa"));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(ulong?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(ulong?), "aaa"));
}
[Fact]
public void Float() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant(float.MinValue));
Assert.Equal(float.MinValue, Utils.GetDataReaderValue(typeof(float), float.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant(float.MaxValue));
Assert.Equal(float.MaxValue, Utils.GetDataReaderValue(typeof(float), float.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant("127"));
Assert.Equal((float)127, Utils.GetDataReaderValue(typeof(float), "127"));
[Fact]
public void Float()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant(float.MinValue));
Assert.Equal(float.MinValue, Utils.GetDataReaderValue(typeof(float), float.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant(float.MaxValue));
Assert.Equal(float.MaxValue, Utils.GetDataReaderValue(typeof(float), float.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant("127"));
Assert.Equal((float)127, Utils.GetDataReaderValue(typeof(float), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant(float.MinValue));
Assert.Equal(float.MinValue, Utils.GetDataReaderValue(typeof(float?), float.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant(float.MaxValue));
Assert.Equal(float.MaxValue, Utils.GetDataReaderValue(typeof(float?), float.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant("127"));
Assert.Equal((float)127, Utils.GetDataReaderValue(typeof(float?), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant(float.MinValue));
Assert.Equal(float.MinValue, Utils.GetDataReaderValue(typeof(float?), float.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant(float.MaxValue));
Assert.Equal(float.MaxValue, Utils.GetDataReaderValue(typeof(float?), float.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant("127"));
Assert.Equal((float)127, Utils.GetDataReaderValue(typeof(float?), "127"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant(null));
Assert.Equal(default(float), Utils.GetDataReaderValue(typeof(float), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant("aaa"));
Assert.Equal(default(float), Utils.GetDataReaderValue(typeof(float), "aaa"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant(null));
Assert.Equal(default(float), Utils.GetDataReaderValue(typeof(float), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant("aaa"));
Assert.Equal(default(float), Utils.GetDataReaderValue(typeof(float), "aaa"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(float?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(float?), "aaa"));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(float?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(float?), "aaa"));
}
[Fact]
public void Double() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant(double.MinValue));
Assert.Equal(double.MinValue, Utils.GetDataReaderValue(typeof(double), double.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant(double.MaxValue));
Assert.Equal(double.MaxValue, Utils.GetDataReaderValue(typeof(double), double.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant("127"));
Assert.Equal((double)127, Utils.GetDataReaderValue(typeof(double), "127"));
[Fact]
public void Double()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant(double.MinValue));
Assert.Equal(double.MinValue, Utils.GetDataReaderValue(typeof(double), double.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant(double.MaxValue));
Assert.Equal(double.MaxValue, Utils.GetDataReaderValue(typeof(double), double.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant("127"));
Assert.Equal((double)127, Utils.GetDataReaderValue(typeof(double), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant(double.MinValue));
Assert.Equal(double.MinValue, Utils.GetDataReaderValue(typeof(double?), double.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant(double.MaxValue));
Assert.Equal(double.MaxValue, Utils.GetDataReaderValue(typeof(double?), double.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant("127"));
Assert.Equal((double)127, Utils.GetDataReaderValue(typeof(double?), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant(double.MinValue));
Assert.Equal(double.MinValue, Utils.GetDataReaderValue(typeof(double?), double.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant(double.MaxValue));
Assert.Equal(double.MaxValue, Utils.GetDataReaderValue(typeof(double?), double.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant("127"));
Assert.Equal((double)127, Utils.GetDataReaderValue(typeof(double?), "127"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant(null));
Assert.Equal(default(double), Utils.GetDataReaderValue(typeof(double), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant("aaa"));
Assert.Equal(default(double), Utils.GetDataReaderValue(typeof(double), "aaa"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant(null));
Assert.Equal(default(double), Utils.GetDataReaderValue(typeof(double), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant("aaa"));
Assert.Equal(default(double), Utils.GetDataReaderValue(typeof(double), "aaa"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(double?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(double?), "aaa"));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(double?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(double?), "aaa"));
}
[Fact]
public void Decimal() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant(decimal.MinValue));
Assert.Equal(decimal.MinValue, Utils.GetDataReaderValue(typeof(decimal), decimal.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant(decimal.MaxValue));
Assert.Equal(decimal.MaxValue, Utils.GetDataReaderValue(typeof(decimal), decimal.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant("127"));
Assert.Equal((decimal)127, Utils.GetDataReaderValue(typeof(decimal), "127"));
[Fact]
public void Decimal()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant(decimal.MinValue));
Assert.Equal(decimal.MinValue, Utils.GetDataReaderValue(typeof(decimal), decimal.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant(decimal.MaxValue));
Assert.Equal(decimal.MaxValue, Utils.GetDataReaderValue(typeof(decimal), decimal.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant("127"));
Assert.Equal((decimal)127, Utils.GetDataReaderValue(typeof(decimal), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant(decimal.MinValue));
Assert.Equal(decimal.MinValue, Utils.GetDataReaderValue(typeof(decimal?), decimal.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant(decimal.MaxValue));
Assert.Equal(decimal.MaxValue, Utils.GetDataReaderValue(typeof(decimal?), decimal.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant("127"));
Assert.Equal((decimal)127, Utils.GetDataReaderValue(typeof(decimal?), "127"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant(decimal.MinValue));
Assert.Equal(decimal.MinValue, Utils.GetDataReaderValue(typeof(decimal?), decimal.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant(decimal.MaxValue));
Assert.Equal(decimal.MaxValue, Utils.GetDataReaderValue(typeof(decimal?), decimal.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant("127"));
Assert.Equal((decimal)127, Utils.GetDataReaderValue(typeof(decimal?), "127"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant(null));
Assert.Equal(default(decimal), Utils.GetDataReaderValue(typeof(decimal), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant("aaa"));
Assert.Equal(default(decimal), Utils.GetDataReaderValue(typeof(decimal), "aaa"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant(null));
Assert.Equal(default(decimal), Utils.GetDataReaderValue(typeof(decimal), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant("aaa"));
Assert.Equal(default(decimal), Utils.GetDataReaderValue(typeof(decimal), "aaa"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(decimal?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(decimal?), "aaa"));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(decimal?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(decimal?), "aaa"));
}
[Fact]
public void DateTime2() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant(DateTime.MinValue));
Assert.Equal(DateTime.MinValue, Utils.GetDataReaderValue(typeof(DateTime), DateTime.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant(DateTime.MaxValue));
Assert.Equal(DateTime.MaxValue, Utils.GetDataReaderValue(typeof(DateTime), DateTime.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant("2000-1-1"));
Assert.Equal(DateTime.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTime), "2000-1-1"));
[Fact]
public void DateTime2()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant(DateTime.MinValue));
Assert.Equal(DateTime.MinValue, Utils.GetDataReaderValue(typeof(DateTime), DateTime.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant(DateTime.MaxValue));
Assert.Equal(DateTime.MaxValue, Utils.GetDataReaderValue(typeof(DateTime), DateTime.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant("2000-1-1"));
Assert.Equal(DateTime.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTime), "2000-1-1"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant(DateTime.MinValue));
Assert.Equal(DateTime.MinValue, Utils.GetDataReaderValue(typeof(DateTime?), DateTime.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant(DateTime.MaxValue));
Assert.Equal(DateTime.MaxValue, Utils.GetDataReaderValue(typeof(DateTime?), DateTime.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant("2000-1-1"));
Assert.Equal(DateTime.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTime?), "2000-1-1"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant(DateTime.MinValue));
Assert.Equal(DateTime.MinValue, Utils.GetDataReaderValue(typeof(DateTime?), DateTime.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant(DateTime.MaxValue));
Assert.Equal(DateTime.MaxValue, Utils.GetDataReaderValue(typeof(DateTime?), DateTime.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant("2000-1-1"));
Assert.Equal(DateTime.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTime?), "2000-1-1"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant(null));
Assert.Equal(default(DateTime), Utils.GetDataReaderValue(typeof(DateTime), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant("aaa"));
Assert.Equal(default(DateTime), Utils.GetDataReaderValue(typeof(DateTime), "aaa"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant(null));
Assert.Equal(default(DateTime), Utils.GetDataReaderValue(typeof(DateTime), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant("aaa"));
Assert.Equal(default(DateTime), Utils.GetDataReaderValue(typeof(DateTime), "aaa"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(DateTime?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(DateTime?), "aaa"));
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(DateTime?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(DateTime?), "aaa"));
}
[Fact]
public void DateTimeOffset2() {
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant(DateTimeOffset.MinValue));
Assert.Equal(DateTimeOffset.MinValue, Utils.GetDataReaderValue(typeof(DateTimeOffset), DateTimeOffset.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant(DateTimeOffset.MaxValue));
Assert.Equal(DateTimeOffset.MaxValue, Utils.GetDataReaderValue(typeof(DateTimeOffset), DateTimeOffset.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant("2000-1-1"));
Assert.Equal(DateTimeOffset.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTimeOffset), "2000-1-1"));
[Fact]
public void DateTimeOffset2()
{
var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant(DateTimeOffset.MinValue));
Assert.Equal(DateTimeOffset.MinValue, Utils.GetDataReaderValue(typeof(DateTimeOffset), DateTimeOffset.MinValue));
var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant(DateTimeOffset.MaxValue));
Assert.Equal(DateTimeOffset.MaxValue, Utils.GetDataReaderValue(typeof(DateTimeOffset), DateTimeOffset.MaxValue));
var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant("2000-1-1"));
Assert.Equal(DateTimeOffset.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTimeOffset), "2000-1-1"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant(DateTimeOffset.MinValue));
Assert.Equal(DateTimeOffset.MinValue, Utils.GetDataReaderValue(typeof(DateTimeOffset?), DateTimeOffset.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant(DateTimeOffset.MaxValue));
Assert.Equal(DateTimeOffset.MaxValue, Utils.GetDataReaderValue(typeof(DateTimeOffset?), DateTimeOffset.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant("2000-1-1"));
Assert.Equal(DateTimeOffset.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTimeOffset?), "2000-1-1"));
var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant(DateTimeOffset.MinValue));
Assert.Equal(DateTimeOffset.MinValue, Utils.GetDataReaderValue(typeof(DateTimeOffset?), DateTimeOffset.MinValue));
var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant(DateTimeOffset.MaxValue));
Assert.Equal(DateTimeOffset.MaxValue, Utils.GetDataReaderValue(typeof(DateTimeOffset?), DateTimeOffset.MaxValue));
var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant("2000-1-1"));
Assert.Equal(DateTimeOffset.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTimeOffset?), "2000-1-1"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant(null));
Assert.Equal(default(DateTimeOffset), Utils.GetDataReaderValue(typeof(DateTimeOffset), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant("aaa"));
Assert.Equal(default(DateTimeOffset), Utils.GetDataReaderValue(typeof(DateTimeOffset), "aaa"));
var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant(null));
Assert.Equal(default(DateTimeOffset), Utils.GetDataReaderValue(typeof(DateTimeOffset), null));
var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant("aaa"));
Assert.Equal(default(DateTimeOffset), Utils.GetDataReaderValue(typeof(DateTimeOffset), "aaa"));
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(DateTimeOffset?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(DateTimeOffset?), "aaa"));
}
}
var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant(null));
Assert.Null(Utils.GetDataReaderValue(typeof(DateTimeOffset?), null));
var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant("aaa"));
Assert.Null(Utils.GetDataReaderValue(typeof(DateTimeOffset?), "aaa"));
}
}
}

View File

@ -3,41 +3,47 @@ using System.Collections.Generic;
using System.Linq.Expressions;
using Xunit;
namespace FreeSql.Tests.Extensions {
public class LambadaExpressionExtensionsTest {
namespace FreeSql.Tests.Extensions
{
public class LambadaExpressionExtensionsTest
{
[Fact]
public void And() {
Expression<Func<testExpAddOr, bool>> where = a => a.id == Guid.Empty;
[Fact]
public void And()
{
Expression<Func<testExpAddOr, bool>> where = a => a.id == Guid.Empty;
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000' AND a.\"num\" > 0)", g.sqlite.Select<testExpAddOr>().Where(where.And(b => b.num > 0)).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select<testExpAddOr>().Where(where.And(false, b => b.num > 0)).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000' AND a.\"num\" = 1 AND a.\"num\" = 2)", g.sqlite.Select<testExpAddOr>().Where(where.And(b => b.num == 1).And(b => b.num == 2)).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select<testExpAddOr>().Where(where.And(false, b => b.num == 1).And(false, c => c.num == 2)).ToSql().Replace("\r\n", ""));
}
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000' AND a.\"num\" > 0)", g.sqlite.Select<testExpAddOr>().Where(where.And(b => b.num > 0)).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select<testExpAddOr>().Where(where.And(false, b => b.num > 0)).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000' AND a.\"num\" = 1 AND a.\"num\" = 2)", g.sqlite.Select<testExpAddOr>().Where(where.And(b => b.num == 1).And(b => b.num == 2)).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select<testExpAddOr>().Where(where.And(false, b => b.num == 1).And(false, c => c.num == 2)).ToSql().Replace("\r\n", ""));
}
[Fact]
public void Or() {
Expression<Func<testExpAddOr, bool>> where = a => a.id == Guid.Empty;
[Fact]
public void Or()
{
Expression<Func<testExpAddOr, bool>> where = a => a.id == Guid.Empty;
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE ((a.\"id\" = '00000000-0000-0000-0000-000000000000' OR a.\"num\" > 0))", g.sqlite.Select<testExpAddOr>().Where(where.Or(b => b.num > 0)).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select<testExpAddOr>().Where(where.Or(false, b => b.num > 0)).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (((a.\"id\" = '00000000-0000-0000-0000-000000000000' OR a.\"num\" = 1) OR a.\"num\" = 2))", g.sqlite.Select<testExpAddOr>().Where(where.Or(b => b.num == 1).Or(b => b.num == 2)).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select<testExpAddOr>().Where(where.Or(false, b => b.num == 1).Or(false, c => c.num == 2)).ToSql().Replace("\r\n", ""));
}
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE ((a.\"id\" = '00000000-0000-0000-0000-000000000000' OR a.\"num\" > 0))", g.sqlite.Select<testExpAddOr>().Where(where.Or(b => b.num > 0)).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select<testExpAddOr>().Where(where.Or(false, b => b.num > 0)).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (((a.\"id\" = '00000000-0000-0000-0000-000000000000' OR a.\"num\" = 1) OR a.\"num\" = 2))", g.sqlite.Select<testExpAddOr>().Where(where.Or(b => b.num == 1).Or(b => b.num == 2)).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select<testExpAddOr>().Where(where.Or(false, b => b.num == 1).Or(false, c => c.num == 2)).ToSql().Replace("\r\n", ""));
}
[Fact]
public void Not() {
Expression<Func<testExpAddOr, bool>> where = a => a.id == Guid.Empty;
[Fact]
public void Not()
{
Expression<Func<testExpAddOr, bool>> where = a => a.id == Guid.Empty;
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (not(a.\"id\" = '00000000-0000-0000-0000-000000000000'))", g.sqlite.Select<testExpAddOr>().Where(where.Not()).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select<testExpAddOr>().Where(where.Not(false)).ToSql().Replace("\r\n", ""));
}
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (not(a.\"id\" = '00000000-0000-0000-0000-000000000000'))", g.sqlite.Select<testExpAddOr>().Where(where.Not()).ToSql().Replace("\r\n", ""));
Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select<testExpAddOr>().Where(where.Not(false)).ToSql().Replace("\r\n", ""));
}
class testExpAddOr {
public Guid id { get; set; }
class testExpAddOr
{
public Guid id { get; set; }
public int num { get; set; }
}
}
public int num { get; set; }
}
}
}

View File

@ -1,65 +1,70 @@
using Xunit;
namespace FreeSql.Tests.Extensions {
public class StringExtensionsTest {
[Fact]
public void FormatMySql() {
namespace FreeSql.Tests.Extensions
{
public class StringExtensionsTest
{
[Fact]
public void FormatMySql()
{
Assert.Empty(((string)null).FormatMySql("11"));
Assert.Equal("a=1", "a={0}".FormatMySql(1));
Assert.Equal("a =1", "a ={0}".FormatMySql(1));
Assert.Equal("a = 1", "a = {0}".FormatMySql(1));
Assert.Equal("a='a'", "a={0}".FormatMySql('a'));
Assert.Equal("a ='a'", "a ={0}".FormatMySql('a'));
Assert.Equal("a = 'a'", "a = {0}".FormatMySql('a'));
Assert.Empty(((string)null).FormatMySql("11"));
Assert.Equal("a=1", "a={0}".FormatMySql(1));
Assert.Equal("a =1", "a ={0}".FormatMySql(1));
Assert.Equal("a = 1", "a = {0}".FormatMySql(1));
Assert.Equal("a='a'", "a={0}".FormatMySql('a'));
Assert.Equal("a ='a'", "a ={0}".FormatMySql('a'));
Assert.Equal("a = 'a'", "a = {0}".FormatMySql('a'));
Assert.Equal("a=1 and b IS NULL", "a={0} and b={1}".FormatMySql(1, null));
Assert.Equal("a =1 and b IS NULL", "a ={0} and b ={1}".FormatMySql(1, null));
Assert.Equal("a = 1 and b IS NULL", "a = {0} and b = {1}".FormatMySql(1, null));
Assert.Equal("a=1 and b IS NULL", "a={0} and b={1}".FormatMySql(1, null));
Assert.Equal("a =1 and b IS NULL", "a ={0} and b ={1}".FormatMySql(1, null));
Assert.Equal("a = 1 and b IS NULL", "a = {0} and b = {1}".FormatMySql(1, null));
Assert.Equal("a=1 and b IS NULL and c in (1,2,3,4)", "a={0} and b={1} and c in {2}".FormatMySql(1, null, new[] { 1, 2, 3, 4 }));
Assert.Equal("a=1 and b IS NULL and c IS NULL", "a={0} and b={1} and c in {2}".FormatMySql(1, null, null));
Assert.Equal("a=1 and b IS NULL and c not IS NULL", "a={0} and b={1} and c not in {2}".FormatMySql(1, null, null));
}
Assert.Equal("a=1 and b IS NULL and c in (1,2,3,4)", "a={0} and b={1} and c in {2}".FormatMySql(1, null, new[] { 1, 2, 3, 4 }));
Assert.Equal("a=1 and b IS NULL and c IS NULL", "a={0} and b={1} and c in {2}".FormatMySql(1, null, null));
Assert.Equal("a=1 and b IS NULL and c not IS NULL", "a={0} and b={1} and c not in {2}".FormatMySql(1, null, null));
}
[Fact]
public void FormatSqlServer() {
[Fact]
public void FormatSqlServer()
{
Assert.Empty(((string)null).FormatSqlServer("11"));
Assert.Equal("a=1", "a={0}".FormatSqlServer(1));
Assert.Equal("a =1", "a ={0}".FormatSqlServer(1));
Assert.Equal("a = 1", "a = {0}".FormatSqlServer(1));
Assert.Equal("a='a'", "a={0}".FormatSqlServer('a'));
Assert.Equal("a ='a'", "a ={0}".FormatSqlServer('a'));
Assert.Equal("a = 'a'", "a = {0}".FormatSqlServer('a'));
Assert.Empty(((string)null).FormatSqlServer("11"));
Assert.Equal("a=1", "a={0}".FormatSqlServer(1));
Assert.Equal("a =1", "a ={0}".FormatSqlServer(1));
Assert.Equal("a = 1", "a = {0}".FormatSqlServer(1));
Assert.Equal("a='a'", "a={0}".FormatSqlServer('a'));
Assert.Equal("a ='a'", "a ={0}".FormatSqlServer('a'));
Assert.Equal("a = 'a'", "a = {0}".FormatSqlServer('a'));
Assert.Equal("a=1 and b IS NULL", "a={0} and b={1}".FormatSqlServer(1, null));
Assert.Equal("a =1 and b IS NULL", "a ={0} and b ={1}".FormatSqlServer(1, null));
Assert.Equal("a = 1 and b IS NULL", "a = {0} and b = {1}".FormatSqlServer(1, null));
Assert.Equal("a=1 and b IS NULL", "a={0} and b={1}".FormatSqlServer(1, null));
Assert.Equal("a =1 and b IS NULL", "a ={0} and b ={1}".FormatSqlServer(1, null));
Assert.Equal("a = 1 and b IS NULL", "a = {0} and b = {1}".FormatSqlServer(1, null));
Assert.Equal("a=1 and b IS NULL and c in (1,2,3,4)", "a={0} and b={1} and c in {2}".FormatSqlServer(1, null, new[] { 1, 2, 3, 4 }));
Assert.Equal("a=1 and b IS NULL and c IS NULL", "a={0} and b={1} and c in {2}".FormatSqlServer(1, null, null));
Assert.Equal("a=1 and b IS NULL and c not IS NULL", "a={0} and b={1} and c not in {2}".FormatSqlServer(1, null, null));
}
Assert.Equal("a=1 and b IS NULL and c in (1,2,3,4)", "a={0} and b={1} and c in {2}".FormatSqlServer(1, null, new[] { 1, 2, 3, 4 }));
Assert.Equal("a=1 and b IS NULL and c IS NULL", "a={0} and b={1} and c in {2}".FormatSqlServer(1, null, null));
Assert.Equal("a=1 and b IS NULL and c not IS NULL", "a={0} and b={1} and c not in {2}".FormatSqlServer(1, null, null));
}
[Fact]
public void FormatPostgreSQL() {
[Fact]
public void FormatPostgreSQL()
{
Assert.Empty(((string)null).FormatPostgreSQL("11"));
Assert.Equal("a=1", "a={0}".FormatPostgreSQL(1));
Assert.Equal("a =1", "a ={0}".FormatPostgreSQL(1));
Assert.Equal("a = 1", "a = {0}".FormatPostgreSQL(1));
Assert.Equal("a='a'", "a={0}".FormatPostgreSQL('a'));
Assert.Equal("a ='a'", "a ={0}".FormatPostgreSQL('a'));
Assert.Equal("a = 'a'", "a = {0}".FormatPostgreSQL('a'));
Assert.Empty(((string)null).FormatPostgreSQL("11"));
Assert.Equal("a=1", "a={0}".FormatPostgreSQL(1));
Assert.Equal("a =1", "a ={0}".FormatPostgreSQL(1));
Assert.Equal("a = 1", "a = {0}".FormatPostgreSQL(1));
Assert.Equal("a='a'", "a={0}".FormatPostgreSQL('a'));
Assert.Equal("a ='a'", "a ={0}".FormatPostgreSQL('a'));
Assert.Equal("a = 'a'", "a = {0}".FormatPostgreSQL('a'));
Assert.Equal("a=1 and b IS NULL", "a={0} and b={1}".FormatPostgreSQL(1, null));
Assert.Equal("a =1 and b IS NULL", "a ={0} and b ={1}".FormatPostgreSQL(1, null));
Assert.Equal("a = 1 and b IS NULL", "a = {0} and b = {1}".FormatPostgreSQL(1, null));
Assert.Equal("a=1 and b IS NULL", "a={0} and b={1}".FormatPostgreSQL(1, null));
Assert.Equal("a =1 and b IS NULL", "a ={0} and b ={1}".FormatPostgreSQL(1, null));
Assert.Equal("a = 1 and b IS NULL", "a = {0} and b = {1}".FormatPostgreSQL(1, null));
Assert.Equal("a=1 and b IS NULL and c in (1,2,3,4)", "a={0} and b={1} and c in {2}".FormatPostgreSQL(1, null, new[] { 1, 2, 3, 4 }));
Assert.Equal("a=1 and b IS NULL and c IS NULL", "a={0} and b={1} and c in {2}".FormatSqlServer(1, null, null));
Assert.Equal("a=1 and b IS NULL and c not IS NULL", "a={0} and b={1} and c not in {2}".FormatSqlServer(1, null, null));
}
}
Assert.Equal("a=1 and b IS NULL and c in (1,2,3,4)", "a={0} and b={1} and c in {2}".FormatPostgreSQL(1, null, new[] { 1, 2, 3, 4 }));
Assert.Equal("a=1 and b IS NULL and c IS NULL", "a={0} and b={1} and c in {2}".FormatSqlServer(1, null, null));
Assert.Equal("a=1 and b IS NULL and c not IS NULL", "a={0} and b={1} and c not in {2}".FormatSqlServer(1, null, null));
}
}
}

View File

@ -3,185 +3,200 @@ using System;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.LinqToSql {
namespace FreeSql.Tests.LinqToSql
{
class TestLinqToSql {
public Guid id { get; set; }
class TestLinqToSql
{
public Guid id { get; set; }
public string name { get; set; }
public string name { get; set; }
public int click { get; set; } = 10;
public int click { get; set; } = 10;
public DateTime createtime { get; set; } = DateTime.Now;
}
class TestLinqToSqlComment {
public Guid id { get; set; }
public DateTime createtime { get; set; } = DateTime.Now;
}
class TestLinqToSqlComment
{
public Guid id { get; set; }
public Guid TestLinqToSqlId { get; set; }
public TestLinqToSql TEstLinqToSql { get; set; }
public Guid TestLinqToSqlId { get; set; }
public TestLinqToSql TEstLinqToSql { get; set; }
public string text { get; set; }
public DateTime createtime { get; set; } = DateTime.Now;
}
public string text { get; set; }
public class SqliteLinqToSqlTests {
public DateTime createtime { get; set; } = DateTime.Now;
}
[Fact]
public void Where() {
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
public class SqliteLinqToSqlTests
{
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
where a.id == item.id
select a).ToList();
Assert.True(t1.Any());
Assert.Equal(item.id, t1[0].id);
}
[Fact]
public void Where()
{
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
[Fact]
public void Select() {
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
where a.id == item.id
select a).ToList();
Assert.True(t1.Any());
Assert.Equal(item.id, t1[0].id);
}
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
where a.id == item.id
select new { a.id }).ToList();
Assert.True(t1.Any());
Assert.Equal(item.id, t1[0].id);
}
[Fact]
public void Select()
{
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
[Fact]
public void GroupBy() {
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
where a.id == item.id
select new { a.id }).ToList();
Assert.True(t1.Any());
Assert.Equal(item.id, t1[0].id);
}
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
where a.id == item.id
group a by new {a.id, a.name } into g
select new {
g.Key.id, g.Key.name,
cou = g.Count(),
avg = g.Avg(g.Value.click),
sum = g.Sum(g.Value.click),
max = g.Max(g.Value.click),
min = g.Min(g.Value.click)
}).ToList();
Assert.True(t1.Any());
Assert.Equal(item.id, t1.First().id);
}
[Fact]
public void GroupBy()
{
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
[Fact]
public void CaseWhen() {
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
where a.id == item.id
group a by new { a.id, a.name } into g
select new
{
g.Key.id,
g.Key.name,
cou = g.Count(),
avg = g.Avg(g.Value.click),
sum = g.Sum(g.Value.click),
max = g.Max(g.Value.click),
min = g.Min(g.Value.click)
}).ToList();
Assert.True(t1.Any());
Assert.Equal(item.id, t1.First().id);
}
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
where a.id == item.id
select new {
a.id,
a.name,
testsub = new {
time = a.click > 10 ? "大于" : "小于或等于"
}
}).ToList();
Assert.True(t1.Any());
Assert.Equal(item.id, t1[0].id);
Assert.Equal("小于或等于", t1[0].testsub.time);
}
[Fact]
public void CaseWhen()
{
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
[Fact]
public void Join() {
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSqlComment>().AppendData(comment).ExecuteAffrows();
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
where a.id == item.id
select new
{
a.id,
a.name,
testsub = new
{
time = a.click > 10 ? "大于" : "小于或等于"
}
}).ToList();
Assert.True(t1.Any());
Assert.Equal(item.id, t1[0].id);
Assert.Equal("小于或等于", t1[0].testsub.time);
}
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId
select a).ToList();
Assert.True(t1.Any());
//Assert.Equal(item.id, t1[0].id);
[Fact]
public void Join()
{
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSqlComment>().AppendData(comment).ExecuteAffrows();
var t2 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId
select new { a.id, bid = b.id }).ToList();
Assert.True(t2.Any());
//Assert.Equal(item.id, t2[0].id);
//Assert.Equal(comment.id, t2[0].bid);
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId
select a).ToList();
Assert.True(t1.Any());
//Assert.Equal(item.id, t1[0].id);
var t3 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId
where a.id == item.id
select new { a.id, bid = b.id }).ToList();
Assert.True(t3.Any());
Assert.Equal(item.id, t3[0].id);
Assert.Equal(comment.id, t3[0].bid);
}
var t2 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId
select new { a.id, bid = b.id }).ToList();
Assert.True(t2.Any());
//Assert.Equal(item.id, t2[0].id);
//Assert.Equal(comment.id, t2[0].bid);
[Fact]
public void LeftJoin() {
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSqlComment>().AppendData(comment).ExecuteAffrows();
var t3 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId
where a.id == item.id
select new { a.id, bid = b.id }).ToList();
Assert.True(t3.Any());
Assert.Equal(item.id, t3[0].id);
Assert.Equal(comment.id, t3[0].bid);
}
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId into temp
from tc in temp.DefaultIfEmpty()
select a).ToList();
Assert.True(t1.Any());
//Assert.Equal(item.id, t1[0].id);
[Fact]
public void LeftJoin()
{
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSqlComment>().AppendData(comment).ExecuteAffrows();
var t2 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId into temp
from tc in temp.DefaultIfEmpty()
select new { a.id, bid = tc.id }).ToList();
Assert.True(t2.Any());
//Assert.Equal(item.id, t2[0].id);
//Assert.Equal(comment.id, t2[0].bid);
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId into temp
from tc in temp.DefaultIfEmpty()
select a).ToList();
Assert.True(t1.Any());
//Assert.Equal(item.id, t1[0].id);
var t3 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId into temp
from tc in temp.DefaultIfEmpty()
where a.id == item.id
select new { a.id, bid = tc.id }).ToList();
Assert.True(t3.Any());
Assert.Equal(item.id, t3[0].id);
Assert.Equal(comment.id, t3[0].bid);
}
var t2 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId into temp
from tc in temp.DefaultIfEmpty()
select new { a.id, bid = tc.id }).ToList();
Assert.True(t2.Any());
//Assert.Equal(item.id, t2[0].id);
//Assert.Equal(comment.id, t2[0].bid);
[Fact]
public void From() {
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSqlComment>().AppendData(comment).ExecuteAffrows();
var t3 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId into temp
from tc in temp.DefaultIfEmpty()
where a.id == item.id
select new { a.id, bid = tc.id }).ToList();
Assert.True(t3.Any());
Assert.Equal(item.id, t3[0].id);
Assert.Equal(comment.id, t3[0].bid);
}
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
from b in g.sqlite.Select<TestLinqToSqlComment>()
where a.id == b.TestLinqToSqlId
select a).ToList();
Assert.True(t1.Any());
//Assert.Equal(item.id, t1[0].id);
[Fact]
public void From()
{
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSqlComment>().AppendData(comment).ExecuteAffrows();
var t2 = (from a in g.sqlite.Select<TestLinqToSql>()
from b in g.sqlite.Select<TestLinqToSqlComment>()
where a.id == b.TestLinqToSqlId
select new { a.id, bid = b.id }).ToList();
Assert.True(t2.Any());
//Assert.Equal(item.id, t2[0].id);
//Assert.Equal(comment.id, t2[0].bid);
var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
from b in g.sqlite.Select<TestLinqToSqlComment>()
where a.id == b.TestLinqToSqlId
select a).ToList();
Assert.True(t1.Any());
//Assert.Equal(item.id, t1[0].id);
var t3 = (from a in g.sqlite.Select<TestLinqToSql>()
from b in g.sqlite.Select<TestLinqToSqlComment>()
where a.id == b.TestLinqToSqlId
where a.id == item.id
select new { a.id, bid = b.id }).ToList();
Assert.True(t3.Any());
Assert.Equal(item.id, t3[0].id);
Assert.Equal(comment.id, t3[0].bid);
}
}
var t2 = (from a in g.sqlite.Select<TestLinqToSql>()
from b in g.sqlite.Select<TestLinqToSqlComment>()
where a.id == b.TestLinqToSqlId
select new { a.id, bid = b.id }).ToList();
Assert.True(t2.Any());
//Assert.Equal(item.id, t2[0].id);
//Assert.Equal(comment.id, t2[0].bid);
var t3 = (from a in g.sqlite.Select<TestLinqToSql>()
from b in g.sqlite.Select<TestLinqToSqlComment>()
where a.id == b.TestLinqToSqlId
where a.id == item.id
select new { a.id, bid = b.id }).ToList();
Assert.True(t3.Any());
Assert.Equal(item.id, t3[0].id);
Assert.Equal(comment.id, t3[0].bid);
}
}
}

View File

@ -4,85 +4,94 @@ using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.MySql {
public class MySqlDeleteTest {
namespace FreeSql.Tests.MySql
{
public class MySqlDeleteTest
{
IDelete<Topic> delete => g.mysql.Delete<Topic>(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
IDelete<Topic> delete => g.mysql.Delete<Topic>(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
[Table(Name = "tb_topic")]
class Topic
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
[Fact]
public void Dywhere() {
Assert.Null(g.mysql.Delete<Topic>().ToSql());
var sql = g.mysql.Delete<Topic>(new[] { 1, 2 }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql);
[Fact]
public void Dywhere()
{
Assert.Null(g.mysql.Delete<Topic>().ToSql());
var sql = g.mysql.Delete<Topic>(new[] { 1, 2 }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new Topic { Id = 1, Title = "test" }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
sql = g.mysql.Delete<Topic>(new Topic { Id = 1, Title = "test" }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
sql = g.mysql.Delete<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new { id = 1 }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
}
sql = g.mysql.Delete<Topic>(new { id = 1 }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
}
[Fact]
public void Where() {
var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
[Fact]
public void Where()
{
var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (id = @id)", sql);
sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (id = @id)", sql);
var item = new Topic { Id = 1, Title = "newtitle" };
sql = delete.Where(item).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
var item = new Topic { Id = 1, Title = "newtitle" };
sql = delete.Where(item).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = delete.Where(items).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
}
[Fact]
public void WhereExists() {
sql = delete.Where(items).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
}
[Fact]
public void WhereExists()
{
}
[Fact]
public void ExecuteAffrows() {
}
[Fact]
public void ExecuteAffrows()
{
var id = g.mysql.Insert<Topic>(new Topic { Title = "xxxx" }).ExecuteIdentity();
Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows());
}
[Fact]
public void ExecuteDeleted() {
var id = g.mysql.Insert<Topic>(new Topic { Title = "xxxx" }).ExecuteIdentity();
Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows());
}
[Fact]
public void ExecuteDeleted()
{
//delete.Where(a => a.Id > 0).ExecuteDeleted();
}
//delete.Where(a => a.Id > 0).ExecuteDeleted();
}
[Fact]
public void AsTable() {
Assert.Null(g.mysql.Delete<Topic>().ToSql());
var sql = g.mysql.Delete<Topic>(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql);
[Fact]
public void AsTable()
{
Assert.Null(g.mysql.Delete<Topic>().ToSql());
var sql = g.mysql.Delete<Topic>(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql);
sql = g.mysql.Delete<Topic>(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql);
sql = g.mysql.Delete<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql);
}
}
sql = g.mysql.Delete<Topic>(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql);
}
}
}

View File

@ -4,133 +4,144 @@ using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.MySql {
public class MySqlInsertTest {
namespace FreeSql.Tests.MySql
{
public class MySqlInsertTest
{
IInsert<Topic> insert => g.mysql.Insert<Topic>(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
IInsert<Topic> insert => g.mysql.Insert<Topic>(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestEnumInsertTb {
[Column(IsIdentity = true)]
public int id { get; set; }
public TestEnumInserTbType type { get; set; }
public DateTime time { get; set; } = new DateTime();
}
enum TestEnumInserTbType { str1, biggit, sum211 }
[Fact]
public void AppendData() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
[Table(Name = "tb_topic")]
class Topic
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestEnumInsertTb
{
[Column(IsIdentity = true)]
public int id { get; set; }
public TestEnumInserTbType type { get; set; }
public DateTime time { get; set; } = new DateTime();
}
enum TestEnumInserTbType { str1, biggit, sum211 }
var sql = insert.AppendData(items.First()).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0)", sql);
[Fact]
public void AppendData()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = insert.AppendData(items).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0), (?Clicks_1, ?Title_1, ?CreateTime_1), (?Clicks_2, ?Title_2, ?CreateTime_2), (?Clicks_3, ?Title_3, ?CreateTime_3), (?Clicks_4, ?Title_4, ?CreateTime_4), (?Clicks_5, ?Title_5, ?CreateTime_5), (?Clicks_6, ?Title_6, ?CreateTime_6), (?Clicks_7, ?Title_7, ?CreateTime_7), (?Clicks_8, ?Title_8, ?CreateTime_8), (?Clicks_9, ?Title_9, ?CreateTime_9)", sql);
var sql = insert.AppendData(items.First()).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0)", sql);
sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql);
sql = insert.AppendData(items).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0), (?Clicks_1, ?Title_1, ?CreateTime_1), (?Clicks_2, ?Title_2, ?CreateTime_2), (?Clicks_3, ?Title_3, ?CreateTime_3), (?Clicks_4, ?Title_4, ?CreateTime_4), (?Clicks_5, ?Title_5, ?CreateTime_5), (?Clicks_6, ?Title_6, ?CreateTime_6), (?Clicks_7, ?Title_7, ?CreateTime_7), (?Clicks_8, ?Title_8, ?CreateTime_8), (?Clicks_9, ?Title_9, ?CreateTime_9)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql);
sql = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211, time = DateTime.Now }).ToSql();
Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES(?type_0, ?time_0)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql);
sql = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ToSql();
Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql);
}
sql = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211, time = DateTime.Now }).ToSql();
Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES(?type_0, ?time_0)", sql);
[Fact]
public void InsertColumns() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ToSql();
Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql);
}
var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql);
[Fact]
public void InsertColumns()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = insert.AppendData(items).InsertColumns(a =>new { a.Title, a.Clicks }).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql);
}
[Fact]
public void IgnoreColumns() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql);
var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql);
}
[Fact]
public void IgnoreColumns()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`) VALUES(?Clicks_0), (?Clicks_1), (?Clicks_2), (?Clicks_3), (?Clicks_4), (?Clicks_5), (?Clicks_6), (?Clicks_7), (?Clicks_8), (?Clicks_9)", sql);
}
[Fact]
public void ExecuteAffrows() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now });
var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql);
Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows());
Assert.Equal(10, insert.AppendData(items).ExecuteAffrows());
sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql();
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`) VALUES(?Clicks_0), (?Clicks_1), (?Clicks_2), (?Clicks_3), (?Clicks_4), (?Clicks_5), (?Clicks_6), (?Clicks_7), (?Clicks_8), (?Clicks_9)", sql);
}
[Fact]
public void ExecuteAffrows()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now });
Assert.Equal(1, g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteAffrows());
Assert.Equal(1, g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteAffrows());
}
[Fact]
public void ExecuteIdentity() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows());
Assert.Equal(10, insert.AppendData(items).ExecuteAffrows());
Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity());
Assert.Equal(1, g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteAffrows());
Assert.Equal(1, g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteAffrows());
}
[Fact]
public void ExecuteIdentity()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
var id = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteIdentity();
Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select< TestEnumInsertTb>().Where(a => a.id == id).First()?.type);
id = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteIdentity();
Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select<TestEnumInsertTb>().Where(a => a.id == id).First()?.type);
}
[Fact]
public void ExecuteInserted() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity());
//insert.AppendData(items.First()).ExecuteInserted();
}
var id = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteIdentity();
Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select<TestEnumInsertTb>().Where(a => a.id == id).First()?.type);
id = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteIdentity();
Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select<TestEnumInsertTb>().Where(a => a.id == id).First()?.type);
}
[Fact]
public void ExecuteInserted()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
[Fact]
public void AsTable() {
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 });
//insert.AppendData(items.First()).ExecuteInserted();
}
var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0)", sql);
[Fact]
public void AsTable()
{
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 });
sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0), (?Clicks_1, ?Title_1, ?CreateTime_1), (?Clicks_2, ?Title_2, ?CreateTime_2), (?Clicks_3, ?Title_3, ?CreateTime_3), (?Clicks_4, ?Title_4, ?CreateTime_4), (?Clicks_5, ?Title_5, ?CreateTime_5), (?Clicks_6, ?Title_6, ?CreateTime_6), (?Clicks_7, ?Title_7, ?CreateTime_7), (?Clicks_8, ?Title_8, ?CreateTime_8), (?Clicks_9, ?Title_9, ?CreateTime_9)", sql);
var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0)", sql);
sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql);
sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0), (?Clicks_1, ?Title_1, ?CreateTime_1), (?Clicks_2, ?Title_2, ?CreateTime_2), (?Clicks_3, ?Title_3, ?CreateTime_3), (?Clicks_4, ?Title_4, ?CreateTime_4), (?Clicks_5, ?Title_5, ?CreateTime_5), (?Clicks_6, ?Title_6, ?CreateTime_6), (?Clicks_7, ?Title_7, ?CreateTime_7), (?Clicks_8, ?Title_8, ?CreateTime_8), (?Clicks_9, ?Title_9, ?CreateTime_9)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql);
sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`) VALUES(?Clicks_0), (?Clicks_1), (?Clicks_2), (?Clicks_3), (?Clicks_4), (?Clicks_5), (?Clicks_6), (?Clicks_7), (?Clicks_8), (?Clicks_9)", sql);
}
}
sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql);
sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql();
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`) VALUES(?Clicks_0), (?Clicks_1), (?Clicks_2), (?Clicks_3), (?Clicks_4), (?Clicks_5), (?Clicks_6), (?Clicks_7), (?Clicks_8), (?Clicks_9)", sql);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -3,185 +3,200 @@ using System;
using System.Collections.Generic;
using Xunit;
namespace FreeSql.Tests.MySql {
public class MySqlUpdateTest {
IUpdate<Topic> update => g.mysql.Update<Topic>();
namespace FreeSql.Tests.MySql
{
public class MySqlUpdateTest
{
IUpdate<Topic> update => g.mysql.Update<Topic>();
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int? Clicks { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestEnumUpdateTb {
[Column(IsIdentity = true)]
public int id { get; set; }
public TestEnumUpdateTbType type { get; set; }
public DateTime time { get; set; } = new DateTime();
}
enum TestEnumUpdateTbType { str1, biggit, sum211 }
[Table(Name = "tb_topic")]
class Topic
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int? Clicks { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestEnumUpdateTb
{
[Column(IsIdentity = true)]
public int id { get; set; }
public TestEnumUpdateTbType type { get; set; }
public DateTime time { get; set; } = new DateTime();
}
enum TestEnumUpdateTbType { str1, biggit, sum211 }
[Fact]
public void Dywhere() {
Assert.Null(g.mysql.Update<Topic>().ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { 1, 2 }).SetRaw("title='test'").ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new { id = 1 }).SetRaw("title='test1'").ToSql());
}
[Fact]
public void Dywhere()
{
Assert.Null(g.mysql.Update<Topic>().ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { 1, 2 }).SetRaw("title='test'").ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql());
Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new { id = 1 }).SetRaw("title='test1'").ToSql());
}
[Fact]
public void SetSource() {
var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ?p_0, `Title` = ?p_1, `CreateTime` = ?p_2 WHERE (`Id` = 1)", sql);
[Fact]
public void SetSource()
{
var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ?p_0, `Title` = ?p_1, `CreateTime` = ?p_2 WHERE (`Id` = 1)", sql);
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = update.SetSource(items).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = CASE `Id` WHEN 1 THEN ?p_0 WHEN 2 THEN ?p_1 WHEN 3 THEN ?p_2 WHEN 4 THEN ?p_3 WHEN 5 THEN ?p_4 WHEN 6 THEN ?p_5 WHEN 7 THEN ?p_6 WHEN 8 THEN ?p_7 WHEN 9 THEN ?p_8 WHEN 10 THEN ?p_9 END, `Title` = CASE `Id` WHEN 1 THEN ?p_10 WHEN 2 THEN ?p_11 WHEN 3 THEN ?p_12 WHEN 4 THEN ?p_13 WHEN 5 THEN ?p_14 WHEN 6 THEN ?p_15 WHEN 7 THEN ?p_16 WHEN 8 THEN ?p_17 WHEN 9 THEN ?p_18 WHEN 10 THEN ?p_19 END, `CreateTime` = CASE `Id` WHEN 1 THEN ?p_20 WHEN 2 THEN ?p_21 WHEN 3 THEN ?p_22 WHEN 4 THEN ?p_23 WHEN 5 THEN ?p_24 WHEN 6 THEN ?p_25 WHEN 7 THEN ?p_26 WHEN 8 THEN ?p_27 WHEN 9 THEN ?p_28 WHEN 10 THEN ?p_29 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = update.SetSource(items).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = CASE `Id` WHEN 1 THEN ?p_0 WHEN 2 THEN ?p_1 WHEN 3 THEN ?p_2 WHEN 4 THEN ?p_3 WHEN 5 THEN ?p_4 WHEN 6 THEN ?p_5 WHEN 7 THEN ?p_6 WHEN 8 THEN ?p_7 WHEN 9 THEN ?p_8 WHEN 10 THEN ?p_9 END, `Title` = CASE `Id` WHEN 1 THEN ?p_10 WHEN 2 THEN ?p_11 WHEN 3 THEN ?p_12 WHEN 4 THEN ?p_13 WHEN 5 THEN ?p_14 WHEN 6 THEN ?p_15 WHEN 7 THEN ?p_16 WHEN 8 THEN ?p_17 WHEN 9 THEN ?p_18 WHEN 10 THEN ?p_19 END, `CreateTime` = CASE `Id` WHEN 1 THEN ?p_20 WHEN 2 THEN ?p_21 WHEN 3 THEN ?p_22 WHEN 4 THEN ?p_23 WHEN 5 THEN ?p_24 WHEN 6 THEN ?p_25 WHEN 7 THEN ?p_26 WHEN 8 THEN ?p_27 WHEN 9 THEN ?p_28 WHEN 10 THEN ?p_29 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = CASE `Id` WHEN 1 THEN ?p_0 WHEN 2 THEN ?p_1 WHEN 3 THEN ?p_2 WHEN 4 THEN ?p_3 WHEN 5 THEN ?p_4 WHEN 6 THEN ?p_5 WHEN 7 THEN ?p_6 WHEN 8 THEN ?p_7 WHEN 9 THEN ?p_8 WHEN 10 THEN ?p_9 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = CASE `Id` WHEN 1 THEN ?p_0 WHEN 2 THEN ?p_1 WHEN 3 THEN ?p_2 WHEN 4 THEN ?p_3 WHEN 5 THEN ?p_4 WHEN 6 THEN ?p_5 WHEN 7 THEN ?p_6 WHEN 8 THEN ?p_7 WHEN 9 THEN ?p_8 WHEN 10 THEN ?p_9 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = update.SetSource(items).Set(a => a.CreateTime, new DateTime(2020,1,1)).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `CreateTime` = ?p_0 WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = update.SetSource(items).Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `CreateTime` = ?p_0 WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES(?type_0, ?time_0)", sql);
var id = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0);
Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES(?type_0, ?time_0)", sql);
var id = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0);
Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = ?p_0, `time` = ?p_1 WHERE (`id` = 0)", sql);
g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = ?p_0, `time` = ?p_1 WHERE (`id` = 0)", sql);
g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Insert<TestEnumUpdateTb>().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql);
id = g.mysql.Insert<TestEnumUpdateTb>().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0);
Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Insert<TestEnumUpdateTb>().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql);
id = g.mysql.Insert<TestEnumUpdateTb>().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0);
Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211', `time` = '0001-01-01 00:00:00.000' WHERE (`id` = 0)", sql);
g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
}
[Fact]
public void IgnoreColumns() {
var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0 WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211', `time` = '0001-01-01 00:00:00.000' WHERE (`id` = 0)", sql);
g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
}
[Fact]
public void IgnoreColumns()
{
var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0 WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = ?p_0 WHERE (`id` = 0)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = ?p_0 WHERE (`id` = 0)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
}
[Fact]
public void UpdateColumns() {
var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0 WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
}
[Fact]
public void UpdateColumns()
{
var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0 WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = ?p_0 WHERE (`id` = 0)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = ?p_0 WHERE (`id` = 0)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
}
[Fact]
public void Set() {
var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0 WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
}
[Fact]
public void Set()
{
var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0 WHERE (`Id` = 1)", sql);
sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0, `CreateTime` = ?p_1 WHERE (`Id` = 1)", sql);
sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0, `CreateTime` = ?p_1 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql);
int incrv = 10;
sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql);
int incrv = 10;
sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = `Clicks` * 10 / 1 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Clicks` = `Clicks` * 10 / 1 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Id` = 10 WHERE (`Id` = 1)", sql);
sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET `Id` = 10 WHERE (`Id` = 1)", sql);
var id = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0);
sql = g.mysql.Update<TestEnumUpdateTb>().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ToSql().Replace("\r\n", "");
Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = ?p_0 WHERE (`id` = {id})", sql);
g.mysql.Update<TestEnumUpdateTb>().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
var id = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0);
sql = g.mysql.Update<TestEnumUpdateTb>().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ToSql().Replace("\r\n", "");
Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = ?p_0 WHERE (`id` = {id})", sql);
g.mysql.Update<TestEnumUpdateTb>().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ToSql().Replace("\r\n", "");
Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = 'str1' WHERE (`id` = {id})", sql);
g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.str1, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
}
[Fact]
public void SetRaw() {
var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + ?incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET clicks = clicks + ?incrClick WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ToSql().Replace("\r\n", "");
Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = 'str1' WHERE (`id` = {id})", sql);
g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ExecuteAffrows();
Assert.Equal(TestEnumUpdateTbType.str1, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
}
[Fact]
public void SetRaw()
{
var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + ?incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET clicks = clicks + ?incrClick WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == 0).SetRaw("`type` = {0}".FormatMySql(TestEnumUpdateTbType.sum211)).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
}
[Fact]
public void Where() {
var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == 0).SetRaw("`type` = {0}".FormatMySql(TestEnumUpdateTbType.sum211)).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
}
[Fact]
public void Where()
{
var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql);
sql = update.Where("id = ?id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (id = ?id)", sql);
sql = update.Where("id = ?id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (id = ?id)", sql);
var item = new Topic { Id = 1, Title = "newtitle" };
sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql);
var item = new Topic { Id = 1, Title = "newtitle" };
sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql);
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == 0 && a.type == TestEnumUpdateTbType.str1)
.Set(a => a.type, TestEnumUpdateTbType.sum211).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0 AND `type` = 'str1')", sql);
}
[Fact]
public void WhereExists() {
sql = g.mysql.Update<TestEnumUpdateTb>().NoneParameter().Where(a => a.id == 0 && a.type == TestEnumUpdateTbType.str1)
.Set(a => a.type, TestEnumUpdateTbType.sum211).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0 AND `type` = 'str1')", sql);
}
[Fact]
public void WhereExists()
{
}
[Fact]
public void ExecuteAffrows() {
}
[Fact]
public void ExecuteAffrows()
{
}
[Fact]
public void ExecuteUpdated() {
}
[Fact]
public void ExecuteUpdated()
{
}
}
[Fact]
public void AsTable() {
Assert.Null(g.mysql.Update<Topic>().ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql());
}
}
[Fact]
public void AsTable()
{
Assert.Null(g.mysql.Update<Topic>().ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql());
Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update<Topic>(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql());
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -3,252 +3,259 @@ using System;
using System.Numerics;
using Xunit;
namespace FreeSql.Tests.MySqlMapType {
public class EnumTest {
class EnumTestMap {
public Guid id { get; set; }
namespace FreeSql.Tests.MySqlMapType
{
public class EnumTest
{
class EnumTestMap
{
public Guid id { get; set; }
[Column(MapType = typeof(string))]
public ToStringMapEnum enum_to_string { get; set; }
[Column(MapType = typeof(string))]
public ToStringMapEnum? enumnullable_to_string { get; set; }
[Column(MapType = typeof(string))]
public ToStringMapEnum enum_to_string { get; set; }
[Column(MapType = typeof(string))]
public ToStringMapEnum? enumnullable_to_string { get; set; }
[Column(MapType = typeof(int))]
public ToStringMapEnum enum_to_int { get; set; }
[Column(MapType = typeof(int?))]
public ToStringMapEnum? enumnullable_to_int { get; set; }
}
public enum ToStringMapEnum { , abc, }
[Fact]
public void EnumToString() {
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
[Column(MapType = typeof(int))]
public ToStringMapEnum enum_to_int { get; set; }
[Column(MapType = typeof(int?))]
public ToStringMapEnum? enumnullable_to_int { get; set; }
}
public enum ToStringMapEnum { , abc, }
[Fact]
public void EnumToString()
{
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_string);
item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_string);
//update all
item.enum_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
//update all
item.enum_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
item.enum_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
item.enum_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_string);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_string);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_string);
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
[Fact]
public void EnumNullableToString() {
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Null(find.enumnullable_to_string);
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
[Fact]
public void EnumNullableToString()
{
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Null(find.enumnullable_to_string);
item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum. };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_string);
item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum. };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_string);
//update all
item.enumnullable_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_string);
//update all
item.enumnullable_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_string);
item.enumnullable_to_string = null;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Null(find.enumnullable_to_string);
item.enumnullable_to_string = null;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Null(find.enumnullable_to_string);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_string);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_string);
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
[Fact]
public void EnumToInt() {
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
[Fact]
public void EnumToInt()
{
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_int);
item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_int);
//update all
item.enum_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
//update all
item.enum_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
item.enum_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
item.enum_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_int);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_int);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_int);
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
[Fact]
public void EnumNullableToInt() {
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Null(find.enumnullable_to_int);
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
[Fact]
public void EnumNullableToInt()
{
//insert
var orm = g.mysql;
var item = new EnumTestMap { };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Null(find.enumnullable_to_int);
item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum. };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_int);
item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum. };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_int);
//update all
item.enumnullable_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_int);
//update all
item.enumnullable_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_int);
item.enumnullable_to_int = null;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Null(find.enumnullable_to_int);
item.enumnullable_to_int = null;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Null(find.enumnullable_to_int);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int);
//update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_int);
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First());
find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find);
Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_int);
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
}
//delete
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(0, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows());
Assert.Equal(1, orm.Delete<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows());
Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -2,53 +2,64 @@ using FreeSql.DataAnnotations;
using System;
using Xunit;
namespace FreeSql.Tests.MySql {
public class MySqlAdoTest {
[Fact]
public void Pool() {
var t1 = g.mysql.Ado.MasterPool.StatisticsFullily;
}
namespace FreeSql.Tests.MySql
{
public class MySqlAdoTest
{
[Fact]
public void Pool()
{
var t1 = g.mysql.Ado.MasterPool.StatisticsFullily;
}
[Fact]
public void SlavePools() {
var t2 = g.mysql.Ado.SlavePools.Count;
}
[Fact]
public void SlavePools()
{
var t2 = g.mysql.Ado.SlavePools.Count;
}
[Fact]
public void ExecuteReader() {
}
[Fact]
public void ExecuteArray() {
}
[Fact]
public void ExecuteNonQuery() {
}
[Fact]
public void ExecuteScalar() {
}
[Fact]
public void ExecuteReader()
{
[Fact]
public void Query() {
var t3 = g.mysql.Ado.Query<xxx>("select * from song");
}
[Fact]
public void ExecuteArray()
{
var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song");
}
[Fact]
public void ExecuteNonQuery()
{
var t5 = g.mysql.Ado.Query<dynamic>("select * from song");
}
}
[Fact]
public void ExecuteScalar()
{
[Fact]
public void QueryMultipline() {
var t3 = g.mysql.Ado.Query<xxx, (int, string, string), dynamic>("select * from song; select * from song; select * from song");
}
}
class xxx {
public int Id { get; set; }
public string Path { get; set; }
public string Title2 { get; set; }
}
}
[Fact]
public void Query()
{
var t3 = g.mysql.Ado.Query<xxx>("select * from song");
var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song");
var t5 = g.mysql.Ado.Query<dynamic>("select * from song");
}
[Fact]
public void QueryMultipline()
{
var t3 = g.mysql.Ado.Query<xxx, (int, string, string), dynamic>("select * from song; select * from song; select * from song");
}
class xxx
{
public int Id { get; set; }
public string Path { get; set; }
public string Title2 { get; set; }
}
}
}

View File

@ -6,80 +6,91 @@ using System.Linq;
using System.Text;
using Xunit;
namespace FreeSql.Tests.MySql {
public class MySqlCodeFirstTest {
namespace FreeSql.Tests.MySql
{
public class MySqlCodeFirstTest
{
[Fact]
public void _字段() {
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<2>();
g.mysql.CodeFirst.SyncStructure<2>();
[Fact]
public void _字段()
{
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<2>();
g.mysql.CodeFirst.SyncStructure<2>();
var item = new 2 {
= "测试标题",
= DateTime.Now
};
Assert.Equal(1, g.mysql.Insert<2>().AppendData(item).ExecuteAffrows());
Assert.NotEqual(Guid.Empty, item.);
var item2 = g.mysql.Select<2>().Where(a => a. == item.).First();
Assert.NotNull(item2);
Assert.Equal(item., item2.);
Assert.Equal(item., item2.);
}
class 2 {
[Column(IsPrimary = true)]
public Guid { get; set; }
var item = new 2
{
= "测试标题",
= DateTime.Now
};
Assert.Equal(1, g.mysql.Insert<2>().AppendData(item).ExecuteAffrows());
Assert.NotEqual(Guid.Empty, item.);
var item2 = g.mysql.Select<2>().Where(a => a. == item.).First();
Assert.NotNull(item2);
Assert.Equal(item., item2.);
Assert.Equal(item., item2.);
}
class 2
{
[Column(IsPrimary = true)]
public Guid { get; set; }
public string { get; set; }
public string { get; set; }
public DateTime { get; set; }
}
public DateTime { get; set; }
}
[Fact]
public void AddUniques() {
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<AddUniquesInfo>();
g.mysql.CodeFirst.SyncStructure<AddUniquesInfo>();
}
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
class AddUniquesInfo {
public Guid id { get; set; }
[Column(Unique = "uk_phone")]
public string phone { get; set; }
[Fact]
public void AddUniques()
{
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<AddUniquesInfo>();
g.mysql.CodeFirst.SyncStructure<AddUniquesInfo>();
}
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
class AddUniquesInfo
{
public Guid id { get; set; }
[Column(Unique = "uk_phone")]
public string phone { get; set; }
[Column(Unique = "uk_group_index, uk_group_index22")]
public string group { get; set; }
[Column(Unique = "uk_group_index")]
public int index { get; set; }
[Column(Unique = "uk_group_index22")]
public string index22 { get; set; }
}
[Column(Unique = "uk_group_index, uk_group_index22")]
public string group { get; set; }
[Column(Unique = "uk_group_index")]
public int index { get; set; }
[Column(Unique = "uk_group_index22")]
public string index22 { get; set; }
}
[Fact]
public void AddField() {
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TopicAddField>();
[Fact]
public void AddField()
{
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TopicAddField>();
var id = g.mysql.Insert<TopicAddField>().AppendData(new TopicAddField { }).ExecuteIdentity();
}
var id = g.mysql.Insert<TopicAddField>().AppendData(new TopicAddField { }).ExecuteIdentity();
}
[Table(Name = "TopicAddField", OldName = "xxxtb.TopicAddField")]
public class TopicAddField {
[Column(IsIdentity = true)]
public int? Id { get; set; }
[Table(Name = "TopicAddField", OldName = "xxxtb.TopicAddField")]
public class TopicAddField
{
[Column(IsIdentity = true)]
public int? Id { get; set; }
public string name { get; set; }
public string name { get; set; }
[Column(DbType = "varchar(200) not null", OldName = "title")]
public string title222 { get; set; } = "10";
[Column(DbType = "varchar(200) not null", OldName = "title")]
public string title222 { get; set; } = "10";
[Column(IsIgnore = true)]
public DateTime ct { get; set; } = DateTime.Now;
}
[Column(IsIgnore = true)]
public DateTime ct { get; set; } = DateTime.Now;
}
[Fact]
public void GetComparisonDDLStatements() {
[Fact]
public void GetComparisonDDLStatements()
{
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TableAllType>();
if (string.IsNullOrEmpty(sql) == false) {
Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` (
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TableAllType>();
if (string.IsNullOrEmpty(sql) == false)
{
Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` (
`Id` INT(11) NOT NULL AUTO_INCREMENT,
`testFieldBool` BIT(1) NOT NULL,
`testFieldSByte` TINYINT(3) NOT NULL,
@ -126,352 +137,363 @@ namespace FreeSql.Tests.MySql {
PRIMARY KEY (`Id`)
) Engine=InnoDB;
", sql);
}
sql = g.mysql.CodeFirst.GetComparisonDDLStatements<Tb_alltype>();
}
IInsert<TableAllType> insert => g.mysql.Insert<TableAllType>();
ISelect<TableAllType> select => g.mysql.Select<TableAllType>();
[Fact]
public void CurdAllField() {
var item = new TableAllType { };
item.Id = (int)insert.AppendData(item).ExecuteIdentity();
var newitem = select.Where(a => a.Id == item.Id).ToOne();
var item2 = new TableAllType {
testFieldBool = true,
testFieldBoolNullable = true,
testFieldByte = 255,
testFieldByteNullable = 127,
testFieldBytes = Encoding.UTF8.GetBytes("我是中国人"),
testFieldDateTime = DateTime.Now,
testFieldDateTimeNullable = DateTime.Now.AddHours(-1),
testFieldDecimal = 99.99M,
testFieldDecimalNullable = 99.98M,
testFieldDouble = 999.99,
testFieldDoubleNullable = 999.98,
testFieldEnum1 = TableAllTypeEnumType1.e5,
testFieldEnum1Nullable = TableAllTypeEnumType1.e3,
testFieldEnum2 = TableAllTypeEnumType2.f2,
testFieldEnum2Nullable = TableAllTypeEnumType2.f3,
testFieldFloat = 19.99F,
testFieldFloatNullable = 19.98F,
testFieldGuid = Guid.NewGuid(),
testFieldGuidNullable = Guid.NewGuid(),
testFieldInt = int.MaxValue,
testFieldIntNullable = int.MinValue,
testFieldLineString = new MygisLineString(new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }),
testFieldLong = long.MaxValue,
testFieldMultiLineString = new MygisMultiLineString(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) },
new[] { new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 100) } }),
testFieldMultiPoint = new MygisMultiPoint(new[] { new MygisCoordinate2D(11, 11), new MygisCoordinate2D(51, 11) }),
testFieldMultiPolygon = new MygisMultiPolygon(new[] {
new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }),
new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }) }),
testFieldPoint = new MygisPoint(99, 99),
testFieldPolygon = new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }),
testFieldSByte = 100,
testFieldSByteNullable = 99,
testFieldShort = short.MaxValue,
testFieldShortNullable = short.MinValue,
testFieldString = "我是中国人string",
testFieldTimeSpan = TimeSpan.FromSeconds(999),
testFieldTimeSpanNullable = TimeSpan.FromSeconds(60),
testFieldUInt = uint.MaxValue,
testFieldUIntNullable = uint.MinValue,
testFieldULong = ulong.MaxValue,
testFieldULongNullable = ulong.MinValue,
testFieldUShort = ushort.MaxValue,
testFieldUShortNullable = ushort.MinValue,
testFielLongNullable = long.MinValue
};
item2.Id = (int)insert.AppendData(item2).ExecuteIdentity();
var newitem2 = select.Where(a => a.Id == item2.Id).ToOne();
}
sql = g.mysql.CodeFirst.GetComparisonDDLStatements<Tb_alltype>();
}
IInsert<TableAllType> insert => g.mysql.Insert<TableAllType>();
ISelect<TableAllType> select => g.mysql.Select<TableAllType>();
[Fact]
public void CurdAllField()
{
var item = new TableAllType { };
item.Id = (int)insert.AppendData(item).ExecuteIdentity();
var newitem = select.Where(a => a.Id == item.Id).ToOne();
var item2 = new TableAllType
{
testFieldBool = true,
testFieldBoolNullable = true,
testFieldByte = 255,
testFieldByteNullable = 127,
testFieldBytes = Encoding.UTF8.GetBytes("我是中国人"),
testFieldDateTime = DateTime.Now,
testFieldDateTimeNullable = DateTime.Now.AddHours(-1),
testFieldDecimal = 99.99M,
testFieldDecimalNullable = 99.98M,
testFieldDouble = 999.99,
testFieldDoubleNullable = 999.98,
testFieldEnum1 = TableAllTypeEnumType1.e5,
testFieldEnum1Nullable = TableAllTypeEnumType1.e3,
testFieldEnum2 = TableAllTypeEnumType2.f2,
testFieldEnum2Nullable = TableAllTypeEnumType2.f3,
testFieldFloat = 19.99F,
testFieldFloatNullable = 19.98F,
testFieldGuid = Guid.NewGuid(),
testFieldGuidNullable = Guid.NewGuid(),
testFieldInt = int.MaxValue,
testFieldIntNullable = int.MinValue,
testFieldLineString = new MygisLineString(new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }),
testFieldLong = long.MaxValue,
testFieldMultiLineString = new MygisMultiLineString(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) },
new[] { new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 100) } }),
testFieldMultiPoint = new MygisMultiPoint(new[] { new MygisCoordinate2D(11, 11), new MygisCoordinate2D(51, 11) }),
testFieldMultiPolygon = new MygisMultiPolygon(new[] {
new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }),
new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }) }),
testFieldPoint = new MygisPoint(99, 99),
testFieldPolygon = new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }),
testFieldSByte = 100,
testFieldSByteNullable = 99,
testFieldShort = short.MaxValue,
testFieldShortNullable = short.MinValue,
testFieldString = "我是中国人string",
testFieldTimeSpan = TimeSpan.FromSeconds(999),
testFieldTimeSpanNullable = TimeSpan.FromSeconds(60),
testFieldUInt = uint.MaxValue,
testFieldUIntNullable = uint.MinValue,
testFieldULong = ulong.MaxValue,
testFieldULongNullable = ulong.MinValue,
testFieldUShort = ushort.MaxValue,
testFieldUShortNullable = ushort.MinValue,
testFielLongNullable = long.MinValue
};
item2.Id = (int)insert.AppendData(item2).ExecuteIdentity();
var newitem2 = select.Where(a => a.Id == item2.Id).ToOne();
var items = select.ToList();
}
var items = select.ToList();
}
[JsonObject(MemberSerialization.OptIn), Table(Name = "tb_alltype")]
public partial class Tb_alltype {
[JsonObject(MemberSerialization.OptIn), Table(Name = "tb_alltype")]
public partial class Tb_alltype
{
[JsonProperty, Column(Name = "Id", DbType = "int(11)", IsPrimary = true, IsIdentity = true)]
public int Id { get; set; }
[JsonProperty, Column(Name = "Id", DbType = "int(11)", IsPrimary = true, IsIdentity = true)]
public int Id { get; set; }
[JsonProperty, Column(Name = "testFieldBool", DbType = "bit(1)")]
public bool TestFieldBool { get; set; }
[JsonProperty, Column(Name = "testFieldBool", DbType = "bit(1)")]
public bool TestFieldBool { get; set; }
[JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit(1)", IsNullable = true)]
public bool? TestFieldBoolNullable { get; set; }
[JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit(1)", IsNullable = true)]
public bool? TestFieldBoolNullable { get; set; }
[JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint(3) unsigned")]
public byte TestFieldByte { get; set; }
[JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint(3) unsigned")]
public byte TestFieldByte { get; set; }
[JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint(3) unsigned", IsNullable = true)]
public byte? TestFieldByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint(3) unsigned", IsNullable = true)]
public byte? TestFieldByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldBytes", DbType = "varbinary(255)", IsNullable = true)]
public byte[] TestFieldBytes { 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 = "testFieldDateTime", DbType = "datetime")]
public DateTime TestFieldDateTime { get; set; }
[JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)]
public DateTime? TestFieldDateTimeNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)]
public DateTime? TestFieldDateTimeNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDecimal", DbType = "decimal(10,2)")]
public decimal TestFieldDecimal { 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 = "testFieldDecimalNullable", DbType = "decimal(10,2)", IsNullable = true)]
public decimal? TestFieldDecimalNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDouble", DbType = "double")]
public double TestFieldDouble { get; set; }
[JsonProperty, Column(Name = "testFieldDouble", DbType = "double")]
public double TestFieldDouble { get; set; }
[JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "double", IsNullable = true)]
public double? TestFieldDoubleNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "double", IsNullable = true)]
public double? TestFieldDoubleNullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1", DbType = "enum('E1','E2','E3','E5')")]
public Tb_alltypeTESTFIELDENUM1 TestFieldEnum1 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1", DbType = "enum('E1','E2','E3','E5')")]
public Tb_alltypeTESTFIELDENUM1 TestFieldEnum1 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "enum('E1','E2','E3','E5')", IsNullable = true)]
public Tb_alltypeTESTFIELDENUM1NULLABLE? TestFieldEnum1Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "enum('E1','E2','E3','E5')", IsNullable = true)]
public Tb_alltypeTESTFIELDENUM1NULLABLE? TestFieldEnum1Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2", DbType = "set('F1','F2','F3')")]
public Tb_alltypeTESTFIELDENUM2 TestFieldEnum2 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2", DbType = "set('F1','F2','F3')")]
public Tb_alltypeTESTFIELDENUM2 TestFieldEnum2 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "set('F1','F2','F3')", IsNullable = true)]
public Tb_alltypeTESTFIELDENUM2NULLABLE? TestFieldEnum2Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "set('F1','F2','F3')", IsNullable = true)]
public Tb_alltypeTESTFIELDENUM2NULLABLE? TestFieldEnum2Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldFloat", DbType = "float")]
public float TestFieldFloat { get; set; }
[JsonProperty, Column(Name = "testFieldFloat", DbType = "float")]
public float TestFieldFloat { get; set; }
[JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "float", IsNullable = true)]
public float? TestFieldFloatNullable { get; set; }
[JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "float", IsNullable = true)]
public float? TestFieldFloatNullable { get; set; }
[JsonProperty, Column(Name = "testFieldGuid", DbType = "char(36)")]
public Guid TestFieldGuid { get; set; }
[JsonProperty, Column(Name = "testFieldGuid", DbType = "char(36)")]
public Guid TestFieldGuid { get; set; }
[JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "char(36)", IsNullable = true)]
public Guid? TestFieldGuidNullable { get; set; }
[JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "char(36)", IsNullable = true)]
public Guid? TestFieldGuidNullable { get; set; }
[JsonProperty, Column(Name = "testFieldInt", DbType = "int(11)")]
public int TestFieldInt { get; set; }
[JsonProperty, Column(Name = "testFieldInt", DbType = "int(11)")]
public int TestFieldInt { get; set; }
[JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int(11)", IsNullable = true)]
public int? TestFieldIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int(11)", IsNullable = true)]
public int? TestFieldIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldLineString", DbType = "linestring", IsNullable = true)]
public MygisGeometry TestFieldLineString { get; set; }
[JsonProperty, Column(Name = "testFieldLineString", DbType = "linestring", IsNullable = true)]
public MygisGeometry TestFieldLineString { get; set; }
[JsonProperty, Column(Name = "testFieldLong", DbType = "bigint(20)")]
public long TestFieldLong { get; set; }
[JsonProperty, Column(Name = "testFieldLong", DbType = "bigint(20)")]
public long TestFieldLong { get; set; }
[JsonProperty, Column(Name = "testFieldMultiLineString", DbType = "multilinestring", IsNullable = true)]
public MygisGeometry TestFieldMultiLineString { get; set; }
[JsonProperty, Column(Name = "testFieldMultiLineString", DbType = "multilinestring", IsNullable = true)]
public MygisGeometry TestFieldMultiLineString { get; set; }
[JsonProperty, Column(Name = "testFieldMultiPoint", DbType = "multipoint", IsNullable = true)]
public MygisGeometry TestFieldMultiPoint { get; set; }
[JsonProperty, Column(Name = "testFieldMultiPoint", DbType = "multipoint", IsNullable = true)]
public MygisGeometry TestFieldMultiPoint { get; set; }
[JsonProperty, Column(Name = "testFieldMultiPolygon", DbType = "multipolygon", IsNullable = true)]
public MygisGeometry TestFieldMultiPolygon { get; set; }
[JsonProperty, Column(Name = "testFieldMultiPolygon", DbType = "multipolygon", IsNullable = true)]
public MygisGeometry TestFieldMultiPolygon { get; set; }
[JsonProperty, Column(Name = "testFieldPoint", DbType = "point", IsNullable = true)]
public MygisGeometry TestFieldPoint { get; set; }
[JsonProperty, Column(Name = "testFieldPoint", DbType = "point", IsNullable = true)]
public MygisGeometry TestFieldPoint { get; set; }
[JsonProperty, Column(Name = "testFieldPolygon", DbType = "polygon", IsNullable = true)]
public MygisGeometry TestFieldPolygon { get; set; }
[JsonProperty, Column(Name = "testFieldPolygon", DbType = "polygon", IsNullable = true)]
public MygisGeometry TestFieldPolygon { get; set; }
[JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint(3)")]
public sbyte TestFieldSByte { get; set; }
[JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint(3)")]
public sbyte TestFieldSByte { get; set; }
[JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint(3)", IsNullable = true)]
public sbyte? TestFieldSByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint(3)", IsNullable = true)]
public sbyte? TestFieldSByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldShort", DbType = "smallint(6)")]
public short TestFieldShort { get; set; }
[JsonProperty, Column(Name = "testFieldShort", DbType = "smallint(6)")]
public short TestFieldShort { get; set; }
[JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint(6)", IsNullable = true)]
public short? TestFieldShortNullable { get; set; }
[JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint(6)", IsNullable = true)]
public short? TestFieldShortNullable { get; set; }
[JsonProperty, Column(Name = "testFieldString", DbType = "varchar(255)", IsNullable = true)]
public string TestFieldString { get; set; }
[JsonProperty, Column(Name = "testFieldString", DbType = "varchar(255)", IsNullable = true)]
public string TestFieldString { get; set; }
[JsonProperty, Column(Name = "testFieldTimeSpan", DbType = "time")]
public TimeSpan TestFieldTimeSpan { 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 = "testFieldTimeSpanNullable", DbType = "time", IsNullable = true)]
public TimeSpan? TestFieldTimeSpanNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUInt", DbType = "int(10) unsigned")]
public uint TestFieldUInt { get; set; }
[JsonProperty, Column(Name = "testFieldUInt", DbType = "int(10) unsigned")]
public uint TestFieldUInt { get; set; }
[JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int(10) unsigned", IsNullable = true)]
public uint? TestFieldUIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int(10) unsigned", IsNullable = true)]
public uint? TestFieldUIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldULong", DbType = "bigint(20) unsigned")]
public ulong TestFieldULong { get; set; }
[JsonProperty, Column(Name = "testFieldULong", DbType = "bigint(20) unsigned")]
public ulong TestFieldULong { get; set; }
[JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint(20) unsigned", IsNullable = true)]
public ulong? TestFieldULongNullable { get; set; }
[JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint(20) unsigned", IsNullable = true)]
public ulong? TestFieldULongNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint(5) unsigned")]
public ushort TestFieldUShort { get; set; }
[JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint(5) unsigned")]
public ushort TestFieldUShort { get; set; }
[JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint(5) unsigned", IsNullable = true)]
public ushort? TestFieldUShortNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint(5) unsigned", IsNullable = true)]
public ushort? TestFieldUShortNullable { get; set; }
[JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint(20)", IsNullable = true)]
public long? TestFielLongNullable { get; set; }
[JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint(20)", IsNullable = true)]
public long? TestFielLongNullable { get; set; }
internal static IFreeSql mysql => null;
public static FreeSql.ISelect<Tb_alltype> Select => mysql.Select<Tb_alltype>();
internal static IFreeSql mysql => null;
public static FreeSql.ISelect<Tb_alltype> Select => mysql.Select<Tb_alltype>();
public static long Delete(int Id) {
var affrows = mysql.Delete<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows();
return affrows;
}
public static long Delete(int Id)
{
var affrows = mysql.Delete<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows();
return affrows;
}
/// <summary>
/// 保存或添加,如果主键有值则尝试 Update如果影响的行为 0 则尝试 Insert
/// </summary>
public void Save() {
if (this.Id != default(int)) {
var affrows = mysql.Update<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows();
if (affrows > 0) return;
}
this.Id = (int)mysql.Insert<Tb_alltype>().AppendData(this).ExecuteIdentity();
}
/// <summary>
/// 保存或添加,如果主键有值则尝试 Update如果影响的行为 0 则尝试 Insert
/// </summary>
public void Save()
{
if (this.Id != default(int))
{
var affrows = mysql.Update<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows();
if (affrows > 0) return;
}
this.Id = (int)mysql.Insert<Tb_alltype>().AppendData(this).ExecuteIdentity();
}
}
}
public enum Tb_alltypeTESTFIELDENUM1 {
E1 = 1, E2, E3, E5
}
public enum Tb_alltypeTESTFIELDENUM1NULLABLE {
E1 = 1, E2, E3, E5
}
[Flags]
public enum Tb_alltypeTESTFIELDENUM2 : long {
F1 = 1, F2 = 2, F3 = 4
}
[Flags]
public enum Tb_alltypeTESTFIELDENUM2NULLABLE : long {
F1 = 1, F2 = 2, F3 = 4
}
public enum Tb_alltypeTESTFIELDENUM1
{
E1 = 1, E2, E3, E5
}
public enum Tb_alltypeTESTFIELDENUM1NULLABLE
{
E1 = 1, E2, E3, E5
}
[Flags]
public enum Tb_alltypeTESTFIELDENUM2 : long
{
F1 = 1, F2 = 2, F3 = 4
}
[Flags]
public enum Tb_alltypeTESTFIELDENUM2NULLABLE : long
{
F1 = 1, F2 = 2, F3 = 4
}
[Table(Name = "tb_alltype")]
class TableAllType {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public bool testFieldBool { get; set; }
public sbyte testFieldSByte { get; set; }
public short testFieldShort { get; set; }
public int testFieldInt { get; set; }
public long testFieldLong { get; set; }
public byte testFieldByte { get; set; }
public ushort testFieldUShort { get; set; }
public uint testFieldUInt { get; set; }
public ulong testFieldULong { get; set; }
public double testFieldDouble { get; set; }
public float testFieldFloat { get; set; }
public decimal testFieldDecimal { get; set; }
public TimeSpan testFieldTimeSpan { get; set; }
public DateTime testFieldDateTime { get; set; }
public byte[] testFieldBytes { get; set; }
public string testFieldString { get; set; }
public Guid testFieldGuid { get; set; }
public bool? testFieldBoolNullable { get; set; }
public sbyte? testFieldSByteNullable { get; set; }
public short? testFieldShortNullable { get; set; }
public int? testFieldIntNullable { get; set; }
public long? testFielLongNullable { get; set; }
public byte? testFieldByteNullable { get; set; }
public ushort? testFieldUShortNullable { get; set; }
public uint? testFieldUIntNullable { get; set; }
public ulong? testFieldULongNullable { get; set; }
public double? testFieldDoubleNullable { get; set; }
public float? testFieldFloatNullable { get; set; }
public decimal? testFieldDecimalNullable { get; set; }
public TimeSpan? testFieldTimeSpanNullable { get; set; }
public DateTime? testFieldDateTimeNullable { get; set; }
public Guid? testFieldGuidNullable { get; set; }
public MygisPoint testFieldPoint { get; set; }
public MygisLineString testFieldLineString { get; set; }
public MygisPolygon testFieldPolygon { get; set; }
public MygisMultiPoint testFieldMultiPoint { get; set; }
public MygisMultiLineString testFieldMultiLineString { get; set; }
public MygisMultiPolygon testFieldMultiPolygon { get; set; }
public TableAllTypeEnumType1 testFieldEnum1 { get; set; }
public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; }
public TableAllTypeEnumType2 testFieldEnum2 { get; set; }
public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; }
}
public enum TableAllTypeEnumType1 { e1, e2, e3, e5 }
[Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 }
}
[Table(Name = "tb_alltype")]
class TableAllType
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public bool testFieldBool { get; set; }
public sbyte testFieldSByte { get; set; }
public short testFieldShort { get; set; }
public int testFieldInt { get; set; }
public long testFieldLong { get; set; }
public byte testFieldByte { get; set; }
public ushort testFieldUShort { get; set; }
public uint testFieldUInt { get; set; }
public ulong testFieldULong { get; set; }
public double testFieldDouble { get; set; }
public float testFieldFloat { get; set; }
public decimal testFieldDecimal { get; set; }
public TimeSpan testFieldTimeSpan { get; set; }
public DateTime testFieldDateTime { get; set; }
public byte[] testFieldBytes { get; set; }
public string testFieldString { get; set; }
public Guid testFieldGuid { get; set; }
public bool? testFieldBoolNullable { get; set; }
public sbyte? testFieldSByteNullable { get; set; }
public short? testFieldShortNullable { get; set; }
public int? testFieldIntNullable { get; set; }
public long? testFielLongNullable { get; set; }
public byte? testFieldByteNullable { get; set; }
public ushort? testFieldUShortNullable { get; set; }
public uint? testFieldUIntNullable { get; set; }
public ulong? testFieldULongNullable { get; set; }
public double? testFieldDoubleNullable { get; set; }
public float? testFieldFloatNullable { get; set; }
public decimal? testFieldDecimalNullable { get; set; }
public TimeSpan? testFieldTimeSpanNullable { get; set; }
public DateTime? testFieldDateTimeNullable { get; set; }
public Guid? testFieldGuidNullable { get; set; }
public MygisPoint testFieldPoint { get; set; }
public MygisLineString testFieldLineString { get; set; }
public MygisPolygon testFieldPolygon { get; set; }
public MygisMultiPoint testFieldMultiPoint { get; set; }
public MygisMultiLineString testFieldMultiLineString { get; set; }
public MygisMultiPolygon testFieldMultiPolygon { get; set; }
public TableAllTypeEnumType1 testFieldEnum1 { get; set; }
public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; }
public TableAllTypeEnumType2 testFieldEnum2 { get; set; }
public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; }
}
public enum TableAllTypeEnumType1 { e1, e2, e3, e5 }
[Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 }
}
}

Some files were not shown because too many files have changed in this diff Show More