源代码改用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 Microsoft.EntityFrameworkCore;
//using SqlSugar; //using SqlSugar;
namespace FreeSql.Bechmarker { namespace FreeSql.Bechmarker
{
public class Program { public class Program
public static void Main(string[] args) { {
var summaryInsert = BenchmarkRunner.Run<OrmVsInsert>(); public static void Main(string[] args)
var summarySelect = BenchmarkRunner.Run<OrmVsSelect>(); {
var summaryUpdate = BenchmarkRunner.Run<OrmVsUpdate>(); var summaryInsert = BenchmarkRunner.Run<OrmVsInsert>();
} var summarySelect = BenchmarkRunner.Run<OrmVsSelect>();
} var summaryUpdate = BenchmarkRunner.Run<OrmVsUpdate>();
}
}
public class Orm { 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") public static IFreeSql fsql = 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=20") .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=20")
.UseAutoSyncStructure(false) //.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")
.UseNoneCommandParameter(true) .UseAutoSyncStructure(false)
//.UseConfigEntityFromDbFirst(true) .UseNoneCommandParameter(true)
.Build(); //.UseConfigEntityFromDbFirst(true)
.Build();
//public static SqlSugarClient sugar { //public static SqlSugarClient sugar {
// get => new SqlSugarClient(new ConnectionConfig() { // get => new SqlSugarClient(new ConnectionConfig() {
// //不欺负让连接池100个最小 // //不欺负让连接池100个最小
// ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20", // ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20",
// DbType = DbType.SqlServer, // 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", // //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, // //DbType = DbType.MySql,
// IsAutoCloseConnection = true, // IsAutoCloseConnection = true,
// InitKeyType = InitKeyType.Attribute // InitKeyType = InitKeyType.Attribute
// }); // });
//} //}
} }
class SongContext : DbContext { class SongContext : DbContext
public DbSet<Song> Songs { get; set; } {
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { public DbSet<Song> Songs { get; set; }
optionsBuilder.UseSqlServer(@"Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=21;Max Pool Size=21"); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
//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"); {
} 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] [CoreJob]
[RPlotExporter, RankColumn] [RPlotExporter, RankColumn]
public class OrmVsInsert { public class OrmVsInsert
public IEnumerable<Song> songs; {
public IEnumerable<Song> songs;
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)] [Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
public int size; public int size;
[GlobalSetup] [GlobalSetup]
public void Setup() { 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)); Orm.fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag));
//sugar创建表失败SqlSugar.SqlSugarException: Sequence contains no elements //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.fsql.Delete<Song>().Where(a => a.Id > 0).ExecuteAffrows();
//Orm.sugar.Deleteable<Song>().Where(a => a.Id > 0).ExecuteCommand(); //Orm.sugar.Deleteable<Song>().Where(a => a.Id > 0).ExecuteCommand();
Orm.fsql.Ado.ExecuteNonQuery("delete from efcore_song"); Orm.fsql.Ado.ExecuteNonQuery("delete from efcore_song");
songs = Enumerable.Range(0, size).Select(a => new Song { songs = Enumerable.Range(0, size).Select(a => new Song
Create_time = DateTime.Now, {
Is_deleted = false, Create_time = DateTime.Now,
Title = $"Insert_{a}", Is_deleted = false,
Url = $"Url_{a}" Title = $"Insert_{a}",
}); Url = $"Url_{a}"
});
//预热 //预热
Orm.fsql.Insert(songs.First()).ExecuteAffrows(); Orm.fsql.Insert(songs.First()).ExecuteAffrows();
//Orm.sugar.Insertable(songs.First()).ExecuteCommand(); //Orm.sugar.Insertable(songs.First()).ExecuteCommand();
using (var db = new SongContext()) { using (var db = new SongContext())
//db.Configuration.AutoDetectChangesEnabled = false; {
db.Songs.AddRange(songs.First()); //db.Configuration.AutoDetectChangesEnabled = false;
db.SaveChanges(); db.Songs.AddRange(songs.First());
} db.SaveChanges();
} }
}
[Benchmark] [Benchmark]
public int FreeSqlInsert() => Orm.fsql.Insert(songs).ExecuteAffrows(); public int FreeSqlInsert() => Orm.fsql.Insert(songs).ExecuteAffrows();
//[Benchmark] //[Benchmark]
//public int SqlSugarInsert() => Orm.sugar.Insertable(songs.ToArray()).ExecuteCommand(); //public int SqlSugarInsert() => Orm.sugar.Insertable(songs.ToArray()).ExecuteCommand();
[Benchmark] [Benchmark]
public int EfCoreInsert() { public int EfCoreInsert()
using (var db = new SongContext()) { {
//db.Configuration.AutoDetectChangesEnabled = false; using (var db = new SongContext())
db.Songs.AddRange(songs.ToArray()); {
return db.SaveChanges(); //db.Configuration.AutoDetectChangesEnabled = false;
} db.Songs.AddRange(songs.ToArray());
} return db.SaveChanges();
} }
}
}
[CoreJob] [CoreJob]
[RPlotExporter, RankColumn] [RPlotExporter, RankColumn]
public class OrmVsUpdate { public class OrmVsUpdate
public List<Song> songs; {
public List<Song> songs;
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)] [Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
public int size; public int size;
[GlobalSetup] [GlobalSetup]
public void Setup() { public void Setup()
songs = Orm.fsql.Select<Song>().Limit(size).ToList(); {
} songs = Orm.fsql.Select<Song>().Limit(size).ToList();
}
[Benchmark] [Benchmark]
public int FreeSqlUpdate() => Orm.fsql.Update<Song>().SetSource(songs).ExecuteAffrows(); public int FreeSqlUpdate() => Orm.fsql.Update<Song>().SetSource(songs).ExecuteAffrows();
//[Benchmark] //[Benchmark]
//public int SqlSugarUpdate() => Orm.sugar.Updateable(songs).ExecuteCommand(); //public int SqlSugarUpdate() => Orm.sugar.Updateable(songs).ExecuteCommand();
[Benchmark] [Benchmark]
public int EfCoreUpdate() { public int EfCoreUpdate()
using (var db = new SongContext()) { {
//db.Configuration.AutoDetectChangesEnabled = false; using (var db = new SongContext())
db.Songs.UpdateRange(songs.ToArray()); {
return db.SaveChanges(); //db.Configuration.AutoDetectChangesEnabled = false;
} db.Songs.UpdateRange(songs.ToArray());
} return db.SaveChanges();
} }
}
}
[CoreJob] [CoreJob]
[RPlotExporter, RankColumn] [RPlotExporter, RankColumn]
public class OrmVsSelect { public class OrmVsSelect
{
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)] [Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
public int size; public int size;
[GlobalSetup] [GlobalSetup]
public void Setup() { public void Setup()
{
}
[Benchmark] }
public List<Song> FreeSqlSelect() => Orm.fsql.Select<Song>().Limit(size).ToList();
//[Benchmark] [Benchmark]
//public List<Song> SqlSugarSelect() => Orm.sugar.Queryable<Song>().Take(size).ToList(); public List<Song> FreeSqlSelect() => Orm.fsql.Select<Song>().Limit(size).ToList();
[Benchmark] //[Benchmark]
public List<Song> EfCoreSelect() { //public List<Song> SqlSugarSelect() => Orm.sugar.Queryable<Song>().Take(size).ToList();
using (var db = new SongContext()) {
return db.Songs.Take(size).AsNoTracking().ToList();
}
}
}
[FreeSql.DataAnnotations.Table(Name = "freesql_song")] [Benchmark]
//[SugarTable("sugar_song")] public List<Song> EfCoreSelect()
[Table("efcore_song")] {
public class Song { using (var db = new SongContext())
[FreeSql.DataAnnotations.Column(IsIdentity = true)] {
//[SugarColumn(IsPrimaryKey = true, IsIdentity = true)] return db.Songs.Take(size).AsNoTracking().ToList();
[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)] [FreeSql.DataAnnotations.Table(Name = "freesql_song")]
[NotMapped] //[SugarTable("sugar_song")]
public virtual ICollection<Tag> Tags { get; set; } [Table("efcore_song")]
} public class Song
[FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")] {
//[SugarTable("sugar_song_tag")] [FreeSql.DataAnnotations.Column(IsIdentity = true)]
[Table("efcore_song_tag")] //[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public class Song_tag { [Key]
public int Song_id { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//[SugarColumn(IsIgnore = true)] public int Id { get; set; }
[NotMapped] public DateTime? Create_time { get; set; }
public virtual Song Song { 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)]
//[SugarColumn(IsIgnore = true)] [NotMapped]
[NotMapped] public virtual ICollection<Tag> Tags { get; set; }
public virtual Tag Tag { get; set; } }
} [FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")]
[FreeSql.DataAnnotations.Table(Name = "freesql_tag")] //[SugarTable("sugar_song_tag")]
//[SugarTable("sugar_tag")] [Table("efcore_song_tag")]
[Table("efcore_tag")] public class Song_tag
public class Tag { {
[FreeSql.DataAnnotations.Column(IsIdentity = true)] public int Song_id { get; set; }
//[SugarColumn(IsPrimaryKey = true, IsIdentity = true)] //[SugarColumn(IsIgnore = true)]
[Key] [NotMapped]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] public virtual Song Song { get; set; }
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 int Tag_id { get; set; }
public string Name { 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)] public decimal? Ddd { get; set; }
[NotMapped] public string Name { get; set; }
public virtual ICollection<Song> Songs { get; set; }
//[SugarColumn(IsIgnore = true)] //[SugarColumn(IsIgnore = true)]
[NotMapped] [NotMapped]
public virtual ICollection<Tag> Tags { get; set; } 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 FreeSql;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace dbcontext_01.Controllers { namespace dbcontext_01.Controllers
[Route("api/[controller]")] {
[ApiController] [Route("api/[controller]")]
public class ValuesController : ControllerBase { [ApiController]
public class ValuesController : ControllerBase
IFreeSql _orm; {
SongContext _songContext;
public ValuesController(SongContext songContext, IFreeSql _orm;
IFreeSql orm1, IFreeSql orm2, SongContext _songContext;
IFreeSql<long> orm3 public ValuesController(SongContext songContext,
) { IFreeSql orm1, IFreeSql orm2,
_songContext = songContext; IFreeSql<long> orm3
_orm = orm1; )
{
_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;
} var adds = Enumerable.Range(0, 100)
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
// GET api/values .ToList();
[HttpGet] //创建一堆无主键值
async public Task<string> Get() {
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.Update(adds);
repos2Song.Where(a => a.Id > 10).ToList(); //批量修改
//查询结果,进入 states
var song = new Song { }; repos2Song.Delete(adds.Skip(10).Take(20).ToList());
repos2Song.Insert(song); //批量删除10-20 元素的主键值会被清除
id = song.Id;
var adds = Enumerable.Range(0, 100) adds.Last().Url = "skldfjlksdjglkjjcccc";
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" }) repos2Song.Update(adds.Last());
.ToList();
//创建一堆无主键值
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"; ctx.UnitOfWork.GetOrBeginTransaction();
repos2Song.Update(adds.Last());
adds.First().Url = "skldfjlksdjglkjjcccc"; var tagAsync = new Tag
repos2Song.Update(adds.First()); {
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; ctx.Songs.Select.Where(a => a.Id > 10).ToList();
var tag = new Tag { //查询结果,进入 states
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);
song = new Song { };
//可插入的 song
ctx.UnitOfWork.GetOrBeginTransaction(); ctx.Songs.Add(song);
id = song.Id;
//因有自增类型立即开启事务执行SQL返回自增值
var tagAsync = new Tag { adds = Enumerable.Range(0, 100)
Name = "testaddsublist", .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
Tags = new[] { .ToList();
new Tag { Name = "sub1" }, //创建一堆无主键值
new Tag { Name = "sub2" },
new Tag {
Name = "sub3",
Tags = new[] {
new Tag { Name = "sub3_01" }
}
}
}
};
await ctx.Tags.AddAsync(tagAsync);
ctx.Songs.AddRange(adds);
//立即执行,将自增值赋给 adds 所有元素,因为有自增类型,如果其他类型,指定传入主键值,不会立即执行
ctx.Songs.Select.Where(a => a.Id > 10).ToList(); for (var a = 0; a < 10; a++)
//查询结果,进入 states adds[a].Title = "dkdkdkdk" + a;
song = new Song { }; ctx.Songs.UpdateRange(adds);
//可插入的 song //批量修改,进入队列
ctx.Songs.Add(song); ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList());
id = song.Id; //批量删除,进入队列,完成时 10-20 元素的主键值会被清除
//因有自增类型立即开启事务执行SQL返回自增值
adds = Enumerable.Range(0, 100) //ctx.Songs.Update(adds.First());
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
.ToList();
//创建一堆无主键值
ctx.Songs.AddRange(adds); adds.Last().Url = "skldfjlksdjglkjjcccc";
//立即执行,将自增值赋给 adds 所有元素,因为有自增类型,如果其他类型,指定传入主键值,不会立即执行 ctx.Songs.Update(adds.Last());
for (var a = 0; a < 10; a++) adds.First().Url = "skldfjlksdjglkjjcccc";
adds[a].Title = "dkdkdkdk" + a; ctx.Songs.Update(adds.First());
ctx.Songs.UpdateRange(adds); //单条修改 urls 的值,进入队列
//批量修改,进入队列
ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList()); //throw new Exception("回滚");
//批量删除,进入队列,完成时 10-20 元素的主键值会被清除
//ctx.Songs.Update(adds.First()); //ctx.Songs.Select.First();
//这里做一个查询,会立即打包【执行队列】,避免没有提交的数据,影响查询结果
adds.Last().Url = "skldfjlksdjglkjjcccc"; ctx.SaveChanges();
ctx.Songs.Update(adds.Last()); //打包【执行队列】,提交事务
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.Update(adds);
reposSong.Where(a => a.Id > 10).ToList(); //批量修改
//查询结果,进入 states
song = new Song { }; reposSong.Delete(adds.Skip(10).Take(20).ToList());
reposSong.Insert(song); //批量删除10-20 元素的主键值会被清除
id = song.Id;
adds = Enumerable.Range(0, 100) adds.Last().Url = "skldfjlksdjglkjjcccc";
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" }) reposSong.Update(adds.Last());
.ToList();
//创建一堆无主键值
reposSong.Insert(adds); adds.First().Url = "skldfjlksdjglkjjcccc";
reposSong.Update(adds.First());
for (var a = 0; a < 10; a++) uow.Commit();
adds[a].Title = "dkdkdkdk" + a; }
reposSong.Update(adds);
//批量修改
reposSong.Delete(adds.Skip(10).Take(20).ToList());
//批量删除10-20 元素的主键值会被清除
adds.Last().Url = "skldfjlksdjglkjjcccc"; //using (var ctx = new SongContext()) {
reposSong.Update(adds.Last());
adds.First().Url = "skldfjlksdjglkjjcccc"; // var song = new Song { };
reposSong.Update(adds.First()); // 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 { }; // //ctx.Songs.Update(adds.First());
// await ctx.Songs.AddAsync(song);
// id = song.Id;
// var adds = Enumerable.Range(0, 100) // adds.Last().Url = "skldfjlksdjglkjjcccc";
// .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" }) // ctx.Songs.Update(adds.Last());
// .ToList();
// await ctx.Songs.AddRangeAsync(adds);
// for (var a = 0; a < adds.Count; a++) // //throw new Exception("回滚");
// adds[a].Title = "dkdkdkdk" + a;
// 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"; return item22.Id.ToString();
// ctx.Songs.Update(adds.Last()); }
// //throw new Exception("回滚"); // GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}
// await ctx.SaveChangesAsync(); // POST api/values
//} [HttpPost]
} catch { public void Post([FromBody] string value)
var item = await _orm.Select<Song>().Where(a => a.Id == id).FirstAsync(); {
}
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(); // DELETE api/values/5
var item33 = await _orm.Select<Song>().Where(a => a.Id > id).ToListAsync(); [HttpDelete("{id}")]
public void Delete(int id)
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) {
}
}
} }

View File

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

View File

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

View File

@ -1,27 +1,27 @@
{ {
"iisSettings": { "iisSettings": {
"windowsAuthentication": false, "windowsAuthentication": false,
"anonymousAuthentication": true, "anonymousAuthentication": true,
"iisExpress": { "iisExpress": {
"applicationUrl": "http://localhost:53030/", "applicationUrl": "http://localhost:53030/",
"sslPort": 0 "sslPort": 0
} }
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}, },
"dbcontext_01": { "profiles": {
"commandName": "Project", "IIS Express": {
"launchBrowser": true, "commandName": "IISExpress",
"environmentVariables": { "launchBrowser": true,
"ASPNETCORE_ENVIRONMENT": "Development" "environmentVariables": {
}, "ASPNETCORE_ENVIRONMENT": "Development"
"applicationUrl": "http://localhost:53031/" }
},
"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; Configuration = configuration;
Fsql = new FreeSql.FreeSqlBuilder() Fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document2.db;Pooling=true;Max Pool Size=10") .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.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") //.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) //.UseSyncStructureToUpper(true)
.UseAutoSyncStructure(true) .UseAutoSyncStructure(true)
.UseLazyLoading(true) .UseLazyLoading(true)
.UseNoneCommandParameter(true) .UseNoneCommandParameter(true)
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText), .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText),
(cmd, log) => Trace.WriteLine(log) (cmd, log) => Trace.WriteLine(log)
) )
.Build(); .Build();
Fsql.Aop.SyncStructureBefore = (s, e) => { Fsql.Aop.SyncStructureBefore = (s, e) =>
Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName))); {
}; 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.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) => { Fsql.Aop.CurdBefore = (s, e) =>
Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + ", " + e.Sql); {
}; 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.CurdAfter = (s, e) =>
}; {
Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + " " + e.ElapsedMilliseconds + "ms, " + e.Sql);
};
Fsql2 = new FreeSql.FreeSqlBuilder() Fsql2 = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document222.db;Pooling=true;Max Pool Size=10") .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") //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true) .UseAutoSyncStructure(true)
.UseLazyLoading(true) .UseLazyLoading(true)
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText), .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText),
(cmd, log) => Trace.WriteLine(log) (cmd, log) => Trace.WriteLine(log)
) )
.Build<long>(); .Build<long>();
} }
enum MySql { } enum MySql { }
enum PgSql { } enum PgSql { }
public IConfiguration Configuration { get; } public IConfiguration Configuration { get; }
public static IFreeSql Fsql { get; private set; } public static IFreeSql Fsql { get; private set; }
public static IFreeSql<long> Fsql2 { get; private set; } public static IFreeSql<long> Fsql2 { get; private set; }
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddMvc(); services.AddMvc();
services.AddSwaggerGen(options => { services.AddSwaggerGen(options =>
options.SwaggerDoc("v1", new Info { {
Version = "v1", options.SwaggerDoc("v1", new Info
Title = "FreeSql.DbContext API" {
}); Version = "v1",
//options.IncludeXmlComments(xmlPath); Title = "FreeSql.DbContext API"
}); });
//options.IncludeXmlComments(xmlPath);
});
services.AddSingleton<IFreeSql>(Fsql); services.AddSingleton<IFreeSql>(Fsql);
services.AddSingleton<IFreeSql<long>>(Fsql2); services.AddSingleton<IFreeSql<long>>(Fsql2);
services.AddFreeDbContext<SongContext>(options => options.UseFreeSql(Fsql)); services.AddFreeDbContext<SongContext>(options => options.UseFreeSql(Fsql));
var sql1 = Fsql.Update<Song>(1).Set(a => a.Id + 10).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 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 sql3 = Fsql.Update<Song>(1).Set(a => a.Create_time.Value.AddHours(1)).ToSql();
} }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); {
Console.OutputEncoding = Encoding.GetEncoding("GB2312"); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.InputEncoding = Encoding.GetEncoding("GB2312"); Console.OutputEncoding = Encoding.GetEncoding("GB2312");
Console.InputEncoding = Encoding.GetEncoding("GB2312");
loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug(); loggerFactory.AddDebug();
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" }); app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
app.UseMvc(); app.UseMvc();
app.UseSwagger(); app.UseSwagger();
app.UseSwaggerUI(c => { app.UseSwaggerUI(c =>
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1"); {
}); c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
} });
} }
}
} }

View File

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

View File

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

View File

@ -2,18 +2,22 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; 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) { protected override void OnModelCreating(ModelBuilder modelBuilder)
base.OnModelCreating(modelBuilder); {
Fsql.CodeFirst.ConfigEntity(modelBuilder.Model); //ͬ²½ÅäÖà 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 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 efcore_to_freesql.Entitys;
using Microsoft.EntityFrameworkCore; 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; } 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>().ToTable("topic1_sss").HasKey(a => a.Id);
modelBuilder.Entity<Topic1>().Property(a => a.Id).HasColumnName("topic1_id").ValueGeneratedOnAdd(); 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 efcore_to_freesql.Entitys;
using Microsoft.EntityFrameworkCore; 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>().ToTable("topic2_sss");
modelBuilder.Entity<Topic2>().Property(a => a.Id).HasColumnName("topic2_id"); modelBuilder.Entity<Topic2>().Property(a => a.Id).HasColumnName("topic2_id");
base.OnModelCreating(modelBuilder); base.OnModelCreating(modelBuilder);
} }
} }
} }

View File

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

View File

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

View File

@ -6,60 +6,67 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; 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"); var relationalTableName = type.FindAnnotation("Relational:TableName");
if (relationalTableName != null) if (relationalTableName != null)
a.Name(relationalTableName.Value?.ToString() ?? type.ClrType.Name); 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"); var relationalColumnName = prop.FindAnnotation("Relational:ColumnName");
if (relationalColumnName != null) if (relationalColumnName != null)
freeProp.Name(relationalColumnName.Value?.ToString() ?? prop.Name); freeProp.Name(relationalColumnName.Value?.ToString() ?? prop.Name);
//主键 //主键
freeProp.IsPrimary(prop.IsPrimaryKey()); freeProp.IsPrimary(prop.IsPrimaryKey());
//自增 //自增
freeProp.IsIdentity( freeProp.IsIdentity(
prop.ValueGenerated == ValueGenerated.Never || prop.ValueGenerated == ValueGenerated.Never ||
prop.ValueGenerated == ValueGenerated.OnAdd || prop.ValueGenerated == ValueGenerated.OnAdd ||
prop.GetAnnotations().Where(z => prop.GetAnnotations().Where(z =>
z.Name == "SqlServer:ValueGenerationStrategy" && z.Value.ToString().Contains("IdentityColumn") //sqlserver 自增 z.Name == "SqlServer:ValueGenerationStrategy" && z.Value.ToString().Contains("IdentityColumn") //sqlserver 自增
|| z.Value.ToString().Contains("IdentityColumn") //其他数据库实现未经测试 || z.Value.ToString().Contains("IdentityColumn") //其他数据库实现未经测试
).Any() ).Any()
); );
//可空 //可空
freeProp.IsNullable(prop.AfterSaveBehavior != PropertySaveBehavior.Throw); freeProp.IsNullable(prop.AfterSaveBehavior != PropertySaveBehavior.Throw);
//类型 //类型
var relationalColumnType = prop.FindAnnotation("Relational:ColumnType"); var relationalColumnType = prop.FindAnnotation("Relational:ColumnType");
if (relationalColumnType != null) { if (relationalColumnType != null)
{
var dbType = relationalColumnType.ToString(); var dbType = relationalColumnType.ToString();
if (!string.IsNullOrEmpty(dbType)) { if (!string.IsNullOrEmpty(dbType))
{
var maxLength = prop.FindAnnotation("MaxLength"); var maxLength = prop.FindAnnotation("MaxLength");
if (maxLength != null) if (maxLength != null)
dbType += $"({maxLength})"; dbType += $"({maxLength})";
freeProp.DbType(dbType); freeProp.DbType(dbType);
} }
} }
} }
}); });
} }
} }
} }

View File

@ -1,30 +1,30 @@
{ {
"$schema": "http://json.schemastore.org/launchsettings.json", "$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": { "iisSettings": {
"windowsAuthentication": false, "windowsAuthentication": false,
"anonymousAuthentication": true, "anonymousAuthentication": true,
"iisExpress": { "iisExpress": {
"applicationUrl": "http://localhost:58143", "applicationUrl": "http://localhost:58143",
"sslPort": 44349 "sslPort": 44349
} }
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}, },
"efcore_to_freesql": { "profiles": {
"commandName": "Project", "IIS Express": {
"launchBrowser": true, "commandName": "IISExpress",
"launchUrl": "api/values", "launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000", "launchUrl": "api/values",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "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; Configuration = configuration;
Fsql = new FreeSql.FreeSqlBuilder() Fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10") .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true) .UseAutoSyncStructure(true)
.Build(); .Build();
DBContexts.BaseDBContext.Fsql = Fsql; DBContexts.BaseDBContext.Fsql = Fsql;
var sql11 = Fsql.Select<Topic1>().ToSql(); var sql11 = Fsql.Select<Topic1>().ToSql();
//SELECT a."Id", a."Title", a."CreateTime" FROM "Topic1" a //SELECT a."Id", a."Title", a."CreateTime" FROM "Topic1" a
var sql12 = Fsql.Insert<Topic1>().AppendData(new Topic1()).ToSql(); var sql12 = Fsql.Insert<Topic1>().AppendData(new Topic1()).ToSql();
//INSERT INTO "Topic1"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0) //INSERT INTO "Topic1"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0)
var sql21 = Fsql.Select<Topic2>().ToSql(); var sql21 = Fsql.Select<Topic2>().ToSql();
//SELECT a."Id", a."Title", a."CreateTime" FROM "Topic2" a //SELECT a."Id", a."Title", a."CreateTime" FROM "Topic2" a
var sql22 = Fsql.Insert<Topic2>().AppendData(new Topic2()).ToSql(); var sql22 = Fsql.Insert<Topic2>().AppendData(new Topic2()).ToSql();
//INSERT INTO "Topic2"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0) //INSERT INTO "Topic2"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0)
using (var db = new Topic1Context()) { using (var db = new Topic1Context())
db.Topic1s.Add(new Topic1()); {
} db.Topic1s.Add(new Topic1());
using (var db = new Topic2Context()) { }
db.Topic2s.Add(new Topic2()); using (var db = new Topic2Context())
} {
db.Topic2s.Add(new Topic2());
}
var sql13 = Fsql.Select<Topic1>().ToSql(); var sql13 = Fsql.Select<Topic1>().ToSql();
//SELECT a."topic1_id", a."Title", a."CreateTime" FROM "topic1_sss" a //SELECT a."topic1_id", a."Title", a."CreateTime" FROM "topic1_sss" a
var sql14 = Fsql.Insert<Topic1>().AppendData(new Topic1()).ToSql(); var sql14 = Fsql.Insert<Topic1>().AppendData(new Topic1()).ToSql();
//INSERT INTO "topic1_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0) //INSERT INTO "topic1_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0)
var sql23 = Fsql.Select<Topic2>().ToSql(); var sql23 = Fsql.Select<Topic2>().ToSql();
//SELECT a."topic2_id", a."Title", a."CreateTime" FROM "topic2_sss" a //SELECT a."topic2_id", a."Title", a."CreateTime" FROM "topic2_sss" a
var sql24 = Fsql.Insert<Topic2>().AppendData(new Topic2()).ToSql(); var sql24 = Fsql.Insert<Topic2>().AppendData(new Topic2()).ToSql();
//INSERT INTO "topic2_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0) //INSERT INTO "topic2_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0)
} }
public IConfiguration Configuration { get; } public IConfiguration Configuration { get; }
public IFreeSql Fsql { get; } public IFreeSql Fsql { get; }
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddSingleton<IFreeSql>(Fsql); services.AddSingleton<IFreeSql>(Fsql);
services.AddMvc(); services.AddMvc();
} }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{ {
loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug(); loggerFactory.AddDebug();
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
app.UseMvc(); app.UseMvc();
} }
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -1,27 +1,27 @@
{ {
"iisSettings": { "iisSettings": {
"windowsAuthentication": false, "windowsAuthentication": false,
"anonymousAuthentication": true, "anonymousAuthentication": true,
"iisExpress": { "iisExpress": {
"applicationUrl": "http://localhost:52751/", "applicationUrl": "http://localhost:52751/",
"sslPort": 0 "sslPort": 0
} }
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}, },
"repository_01": { "profiles": {
"commandName": "Project", "IIS Express": {
"launchBrowser": true, "commandName": "IISExpress",
"environmentVariables": { "launchBrowser": true,
"ASPNETCORE_ENVIRONMENT": "Development" "environmentVariables": {
}, "ASPNETCORE_ENVIRONMENT": "Development"
"applicationUrl": "http://localhost:52752/" }
},
"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.Linq;
using System.Text; using System.Text;
namespace repository_01 { namespace repository_01
{
/// <summary> /// <summary>
/// 用户密码信息 /// 用户密码信息
/// </summary> /// </summary>
public class Sys1UserLogOn { public class Sys1UserLogOn
[Column(IsPrimary = true, Name = "Id")] {
public Guid UserLogOnId { get; set; } [Column(IsPrimary = true, Name = "Id")]
public virtual Sys1User User { get; set; } public Guid UserLogOnId { get; set; }
} public virtual Sys1User User { get; set; }
public class Sys1User { }
[Column(IsPrimary = true, Name = "Id")] public class Sys1User
public Guid UserId { get; set; } {
public virtual Sys1UserLogOn UserLogOn { get; set; } [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;
Fsql = new FreeSql.FreeSqlBuilder() public class Startup
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10") {
.UseAutoSyncStructure(true) public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
.UseLazyLoading(true) {
Configuration = configuration;
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText)) Fsql = new FreeSql.FreeSqlBuilder()
.Build(); .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
var sysu = new Sys1User { }; .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
Fsql.Insert<Sys1User>().AppendData(sysu).ExecuteAffrows(); .Build();
Fsql.Insert<Sys1UserLogOn>().AppendData(new Sys1UserLogOn { UserLogOnId = sysu.UserId }).ExecuteAffrows();
var a = Fsql.Select<Sys1UserLogOn>().ToList();
var b = Fsql.Select<Sys1UserLogOn>().Any();
}
public IConfiguration Configuration { get; } var sysu = new Sys1User { };
public static IFreeSql Fsql { get; private set; } 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.AddTransient(s => s.)
services.AddSwaggerGen(options => {
options.SwaggerDoc("v1", new Info {
Version = "v1",
Title = "FreeSql.RESTful API"
});
//options.IncludeXmlComments(xmlPath);
});
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 => { services.AddSingleton<IFreeSql>(Fsql);
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);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { services.AddFreeRepository(filter =>
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); {
Console.OutputEncoding = Encoding.GetEncoding("GB2312"); filter
Console.InputEncoding = Encoding.GetEncoding("GB2312"); //.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")); public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
loggerFactory.AddDebug(); {
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
Console.InputEncoding = Encoding.GetEncoding("GB2312");
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" }); loggerFactory.AddConsole(Configuration.GetSection("Logging"));
app.UseDeveloperExceptionPage(); loggerFactory.AddDebug();
app.UseMvc();
app.UseSwagger(); app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
app.UseSwaggerUI(c => { app.UseDeveloperExceptionPage();
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1"); app.UseMvc();
});
}
}
public interface ISoftDelete { app.UseSwagger();
bool IsDeleted { get; set; } 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": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Debug", "Default": "Debug",
"System": "Warning", "System": "Warning",
"Microsoft": "Warning" "Microsoft": "Warning"
} }
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -5,150 +5,168 @@ using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FreeSql { namespace FreeSql
public abstract partial class DbContext : IDisposable { {
public abstract partial class DbContext : IDisposable
{
internal IFreeSql _orm; internal IFreeSql _orm;
internal IFreeSql _fsql => _orm ?? throw new ArgumentNullException("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql"); internal IFreeSql _fsql => _orm ?? throw new ArgumentNullException("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql");
public IFreeSql Orm => _fsql; public IFreeSql Orm => _fsql;
protected IUnitOfWork _uowPriv; protected IUnitOfWork _uowPriv;
internal IUnitOfWork _uow => _isUseUnitOfWork ? (_uowPriv ?? (_uowPriv = new UnitOfWork(_fsql))) : null; internal IUnitOfWork _uow => _isUseUnitOfWork ? (_uowPriv ?? (_uowPriv = new UnitOfWork(_fsql))) : null;
internal bool _isUseUnitOfWork = true; //不使用工作单元事务 internal bool _isUseUnitOfWork = true; //不使用工作单元事务
public IUnitOfWork UnitOfWork => _uow; public IUnitOfWork UnitOfWork => _uow;
DbContextOptions _options; DbContextOptions _options;
internal DbContextOptions Options { internal DbContextOptions Options
get { {
if (_options != null) return _options; get
if (FreeSqlDbContextExtenssions._dicSetDbContextOptions.TryGetValue(Orm, out _options)) return _options; {
_options = new DbContextOptions(); if (_options != null) return _options;
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[]>(); static ConcurrentDictionary<Type, PropertyInfo[]> _dicGetDbSetProps = new ConcurrentDictionary<Type, PropertyInfo[]>();
protected DbContext() { protected DbContext()
{
var builder = new DbContextOptionsBuilder(); var builder = new DbContextOptionsBuilder();
OnConfiguring(builder); OnConfiguring(builder);
_orm = builder._fsql; _orm = builder._fsql;
if (_orm != null) InitPropSets(); if (_orm != null) InitPropSets();
} }
internal void InitPropSets() { internal void InitPropSets()
var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp => {
tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public) var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp =>
.Where(a => a.PropertyType.IsGenericType && tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray()); .Where(a => a.PropertyType.IsGenericType &&
a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray());
foreach (var prop in props) { foreach (var prop in props)
var set = this.Set(prop.PropertyType.GenericTypeArguments[0]); {
var set = this.Set(prop.PropertyType.GenericTypeArguments[0]);
prop.SetValue(this, set); prop.SetValue(this, set);
AllSets.Add(prop.Name, 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 protected Dictionary<Type, IDbSet> _dicSet = new Dictionary<Type, IDbSet>();
/// <summary> public DbSet<TEntity> Set<TEntity>() where TEntity : class => this.Set(typeof(TEntity)) as DbSet<TEntity>;
/// 添加 public virtual IDbSet Set(Type entityType)
/// </summary> {
/// <typeparam name="TEntity"></typeparam> if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType];
/// <param name="data"></param> var sd = Activator.CreateInstance(typeof(DbContextDbSet<>).MakeGenericType(entityType), this) as IDbSet;
public void Add<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Add(data); if (entityType != typeof(object)) _dicSet.Add(entityType, sd);
public void AddRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AddRange(data); return sd;
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<string, IDbSet> AllSets { get; } = new Dictionary<string, IDbSet>();
/// <summary> #region DbSet
/// 更新 /// <summary>
/// </summary> /// 添加
/// <typeparam name="TEntity"></typeparam> /// </summary>
/// <param name="data"></param> /// <typeparam name="TEntity"></typeparam>
public void Update<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Update(data); /// <param name="data"></param>
public void UpdateRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().UpdateRange(data); public void Add<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Add(data);
public Task UpdateAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().UpdateAsync(data); public void AddRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AddRange(data);
public Task UpdateRangeAsync<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().UpdateRangeAsync(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>
/// 删除 /// 更新
/// </summary> /// </summary>
/// <typeparam name="TEntity"></typeparam> /// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param> /// <param name="data"></param>
public void Remove<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Remove(data); public void Update<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Update(data);
public void RemoveRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().RemoveRange(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>
/// 添加或更新 /// 删除
/// </summary> /// </summary>
/// <typeparam name="TEntity"></typeparam> /// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param> /// <param name="data"></param>
public void AddOrUpdate<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddOrUpdate(data); public void Remove<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Remove(data);
public Task AddOrUpdateAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddOrUpdateAsync(data); public void RemoveRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().RemoveRange(data);
/// <summary> /// <summary>
/// 附加实体,可用于不查询就更新或删除 /// 添加或更新
/// </summary> /// </summary>
/// <typeparam name="TEntity"></typeparam> /// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param> /// <param name="data"></param>
public void Attach<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Attach(data); public void AddOrUpdate<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddOrUpdate(data);
public void AttachRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AttachRange(data); public Task AddOrUpdateAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddOrUpdateAsync(data);
#endregion
internal class ExecCommandInfo { /// <summary>
public ExecCommandInfoType actionType { get; set; } /// 附加实体,可用于不查询就更新或删除
public IDbSet dbSet { get; set; } /// </summary>
public Type stateType { get; set; } /// <typeparam name="TEntity"></typeparam>
public object state { get; set; } /// <param name="data"></param>
} public void Attach<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Attach(data);
internal enum ExecCommandInfoType { Insert, Update, Delete } public void AttachRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AttachRange(data);
Queue<ExecCommandInfo> _actions = new Queue<ExecCommandInfo>(); #endregion
internal int _affrows = 0;
internal void EnqueueAction(ExecCommandInfoType actionType, IDbSet dbSet, Type stateType, object state) { internal class ExecCommandInfo
_actions.Enqueue(new ExecCommandInfo { actionType = actionType, dbSet = dbSet, stateType = stateType, state = state }); {
} 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() { internal void EnqueueAction(ExecCommandInfoType actionType, IDbSet dbSet, Type stateType, object state)
this.Dispose(); {
} _actions.Enqueue(new ExecCommandInfo { actionType = actionType, dbSet = dbSet, stateType = stateType, state = state });
bool _isdisposed = false; }
public void Dispose() {
if (_isdisposed) return;
try {
_actions.Clear();
foreach (var set in _dicSet) ~DbContext()
try { {
set.Value.Dispose(); this.Dispose();
} catch { } }
bool _isdisposed = false;
public void Dispose()
{
if (_isdisposed) return;
try
{
_actions.Clear();
_dicSet.Clear(); foreach (var set in _dicSet)
AllSets.Clear(); try
{
_uow?.Rollback(); set.Value.Dispose();
} finally { }
_isdisposed = true; catch { }
GC.SuppressFinalize(this);
} _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.Linq.Expressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FreeSql { namespace FreeSql
partial class DbContext { {
partial class DbContext
{
async public virtual Task<int> SaveChangesAsync() { async public virtual Task<int> SaveChangesAsync()
await ExecCommandAsync(); {
_uow?.Commit(); await ExecCommandAsync();
var ret = _affrows; _uow?.Commit();
_affrows = 0; var ret = _affrows;
return ret; _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>>>>(); 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() { async internal Task ExecCommandAsync()
if (isExecCommanding) return; {
if (_actions.Any() == false) return; if (isExecCommanding) return;
isExecCommanding = true; if (_actions.Any() == false) return;
isExecCommanding = true;
ExecCommandInfo oldinfo = null; ExecCommandInfo oldinfo = null;
var states = new List<object>(); var states = new List<object>();
Func<string, Task<int>> dbContextBetch = methodName => { 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 (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
if (trydic.TryGetValue(methodName, out var tryfunc) == false) { trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
var arrType = oldinfo.stateType.MakeArrayType(); if (trydic.TryGetValue(methodName, out var tryfunc) == false)
var dbsetType = oldinfo.dbSet.GetType().BaseType; {
var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null); 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 returnTarget = Expression.Label(typeof(Task<int>));
var parm1DbSet = Expression.Parameter(typeof(object)); var parm1DbSet = Expression.Parameter(typeof(object));
var parm2Vals = Expression.Parameter(typeof(object[])); var parm2Vals = Expression.Parameter(typeof(object[]));
var var1Vals = Expression.Variable(arrType); var var1Vals = Expression.Variable(arrType);
tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block( tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
new[] { var1Vals }, new[] { var1Vals },
Expression.Assign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)), 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.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
Expression.Label(returnTarget, Expression.Default(typeof(Task<int>))) Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
), new[] { parm1DbSet, parm2Vals }).Compile(); ), new[] { parm1DbSet, parm2Vals }).Compile();
trydic.Add(methodName, tryfunc); trydic.Add(methodName, tryfunc);
} }
return tryfunc(oldinfo.dbSet, states.ToArray()); return tryfunc(oldinfo.dbSet, states.ToArray());
}; };
Func<Task> funcDelete = async () => { Func<Task> funcDelete = async () =>
_affrows += await dbContextBetch("DbContextBetchRemoveAsync"); {
states.Clear(); _affrows += await dbContextBetch("DbContextBetchRemoveAsync");
}; states.Clear();
Func<Task> funcInsert = async () => { };
_affrows += await dbContextBetch("DbContextBetchAddAsync"); Func<Task> funcInsert = async () =>
states.Clear(); {
}; _affrows += await dbContextBetch("DbContextBetchAddAsync");
Func<bool, Task> funcUpdate = async (isLiveUpdate) => { states.Clear();
var affrows = 0; };
if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync"); Func<bool, Task> funcUpdate = async (isLiveUpdate) =>
else affrows = await dbContextBetch("DbContextBetchUpdateAsync"); {
if (affrows == -999) { //最后一个元素已被删除 var affrows = 0;
states.RemoveAt(states.Count - 1); if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
return; else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
} if (affrows == -999)
if (affrows == -998 || affrows == -997) { //没有执行更新 { //最后一个元素已被删除
var laststate = states[states.Count - 1]; states.RemoveAt(states.Count - 1);
states.Clear(); return;
if (affrows == -997) states.Add(laststate); //保留最后一个 }
} if (affrows == -998 || affrows == -997)
if (affrows > 0) { { //没有执行更新
_affrows += affrows; var laststate = states[states.Count - 1];
var islastNotUpdated = states.Count != affrows; states.Clear();
var laststate = states[states.Count - 1]; if (affrows == -997) states.Add(laststate); //保留最后一个
states.Clear(); }
if (islastNotUpdated) 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()) { while (_actions.Any() || states.Any())
var info = _actions.Any() ? _actions.Dequeue() : null; {
if (oldinfo == null) oldinfo = info; var info = _actions.Any() ? _actions.Dequeue() : null;
var isLiveUpdate = false; if (oldinfo == null) oldinfo = info;
var isLiveUpdate = false;
if (_actions.Any() == false && states.Any() || if (_actions.Any() == false && states.Any() ||
info != null && oldinfo.actionType != info.actionType || info != null && oldinfo.actionType != info.actionType ||
info != null && oldinfo.stateType != info.stateType) { info != null && oldinfo.stateType != info.stateType)
{
if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) { if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType)
//最后一个,合起来发送 {
states.Add(info.state); //最后一个,合起来发送
info = null; states.Add(info.state);
} info = null;
}
switch (oldinfo.actionType) { switch (oldinfo.actionType)
case ExecCommandInfoType.Insert: {
await funcInsert(); case ExecCommandInfoType.Insert:
break; await funcInsert();
case ExecCommandInfoType.Delete: break;
await funcDelete(); case ExecCommandInfoType.Delete:
break; await funcDelete();
} break;
isLiveUpdate = true; }
} isLiveUpdate = true;
}
if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) { if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update)
if (states.Any()) {
await funcUpdate(isLiveUpdate); if (states.Any())
} await funcUpdate(isLiveUpdate);
}
if (info != null) { if (info != null)
states.Add(info.state); {
oldinfo = info; states.Add(info.state);
} oldinfo = info;
} }
isExecCommanding = false; }
} isExecCommanding = false;
} }
}
} }

View File

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

View File

@ -1,13 +1,16 @@
 
namespace FreeSql { namespace FreeSql
public class DbContextOptionsBuilder { {
public class DbContextOptionsBuilder
{
internal IFreeSql _fsql; internal IFreeSql _fsql;
public DbContextOptionsBuilder UseFreeSql(IFreeSql orm) { public DbContextOptionsBuilder UseFreeSql(IFreeSql orm)
_fsql = orm; {
return this; _fsql = orm;
} return this;
} }
}
} }

View File

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

View File

@ -1,10 +1,13 @@
 
namespace FreeSql { namespace FreeSql
public class FreeContext : DbContext { {
public class FreeContext : DbContext
{
public FreeContext(IFreeSql orm) { public FreeContext(IFreeSql orm)
_orm = orm; {
} _orm = orm;
} }
}
} }

View File

@ -8,274 +8,326 @@ using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Reflection; 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) { public DbContextDbSet(DbContext ctx)
_ctx = ctx; {
_uow = ctx._uow; _ctx = ctx;
_fsql = ctx._fsql; _uow = ctx._uow;
} _fsql = ctx._fsql;
} }
}
public interface IDbSet : IDisposable { public interface IDbSet : IDisposable
Type EntityType { get; } {
} Type EntityType { get; }
public abstract partial class DbSet<TEntity> : IDbSet where TEntity : class { }
public abstract partial class DbSet<TEntity> : IDbSet where TEntity : class
{
internal DbContext _ctx; internal DbContext _ctx;
internal IUnitOfWork _uow; internal IUnitOfWork _uow;
internal IFreeSql _fsql; internal IFreeSql _fsql;
protected virtual ISelect<TEntity> OrmSelect(object dywhere) { protected virtual ISelect<TEntity> OrmSelect(object dywhere)
DbContextExecCommand(); //查询前先提交,否则会出脏读 {
return _fsql.Select<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction(false)).TrackToList(TrackToList).WhereDynamic(dywhere); DbContextExecCommand(); //查询前先提交,否则会出脏读
} return _fsql.Select<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction(false)).TrackToList(TrackToList).WhereDynamic(dywhere);
}
~DbSet() { ~DbSet()
this.Dispose(); {
} this.Dispose();
bool _isdisposed = false; }
public void Dispose() { bool _isdisposed = false;
if (_isdisposed) return; public void Dispose()
try { {
this._dicUpdateTimes.Clear(); if (_isdisposed) return;
this._states.Clear(); try
} finally { {
_isdisposed = true; this._dicUpdateTimes.Clear();
GC.SuppressFinalize(this); 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() => _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(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(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 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 IDelete<TEntity> OrmDelete(object dywhere) => _fsql.Delete<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).WhereDynamic(dywhere);
internal void EnqueueToDbContext(DbContext.ExecCommandInfoType actionType, EntityState state) { internal void EnqueueToDbContext(DbContext.ExecCommandInfoType actionType, EntityState state)
_ctx.EnqueueAction(actionType, this, typeof(EntityState), state); {
} _ctx.EnqueueAction(actionType, this, typeof(EntityState), state);
internal void IncrAffrows(int affrows) { }
_ctx._affrows += affrows; internal void IncrAffrows(int affrows)
} {
_ctx._affrows += affrows;
}
internal void TrackToList(object list) { internal void TrackToList(object list)
if (list == null) return; {
var ls = list as IList<TEntity>; if (list == null) return;
if (ls == null) { var ls = list as IList<TEntity>;
var ie = list as IEnumerable; if (ls == null)
if (ie == null) return; {
foreach (var item in ie) { var ie = list as IEnumerable;
if (item == null) return; if (ie == null) return;
var itemType = item.GetType(); foreach (var item in ie)
if (itemType == typeof(object)) return; {
if (itemType.FullName.StartsWith("Submission#")) itemType = itemType.BaseType; if (item == null) return;
var dbset = _ctx.Set(itemType); var itemType = item.GetType();
dbset?.GetType().GetMethod("TrackToList", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(dbset, new object[] { list }); if (itemType == typeof(object)) return;
return; if (itemType.FullName.StartsWith("Submission#")) itemType = itemType.BaseType;
} var dbset = _ctx.Set(itemType);
return; dbset?.GetType().GetMethod("TrackToList", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(dbset, new object[] { list });
} return;
}
return;
}
foreach (var item in ls) { foreach (var item in ls)
var key = _fsql.GetEntityKeyString(_entityType, item, false); {
if (key == null) continue; var key = _fsql.GetEntityKeyString(_entityType, item, false);
_states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) => { if (key == null) continue;
_fsql.MapEntityValue(_entityType, item, ov.Value); _states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) =>
ov.Time = DateTime.Now; {
return ov; _fsql.MapEntityValue(_entityType, item, ov.Value);
}); ov.Time = DateTime.Now;
} return ov;
} });
}
}
public ISelect<TEntity> Select => this.OrmSelect(null); public ISelect<TEntity> Select => this.OrmSelect(null);
public ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => this.OrmSelect(null).Where(exp); 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> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp) => this.OrmSelect(null).WhereIf(condition, exp);
protected ConcurrentDictionary<string, EntityState> _states = new ConcurrentDictionary<string, EntityState>(); protected ConcurrentDictionary<string, EntityState> _states = new ConcurrentDictionary<string, EntityState>();
internal ConcurrentDictionary<string, EntityState> _statesInternal => _states; internal ConcurrentDictionary<string, EntityState> _statesInternal => _states;
TableInfo _tablePriv; TableInfo _tablePriv;
protected TableInfo _table => _tablePriv ?? (_tablePriv = _fsql.CodeFirst.GetTableByEntity(_entityType)); protected TableInfo _table => _tablePriv ?? (_tablePriv = _fsql.CodeFirst.GetTableByEntity(_entityType));
ColumnInfo[] _tableIdentitysPriv; ColumnInfo[] _tableIdentitysPriv;
protected ColumnInfo[] _tableIdentitys => _tableIdentitysPriv ?? (_tableIdentitysPriv = _table.Primarys.Where(a => a.Attribute.IsIdentity).ToArray()); protected ColumnInfo[] _tableIdentitys => _tableIdentitysPriv ?? (_tableIdentitysPriv = _table.Primarys.Where(a => a.Attribute.IsIdentity).ToArray());
protected Type _entityType = typeof(TEntity); protected Type _entityType = typeof(TEntity);
public Type EntityType => _entityType; public Type EntityType => _entityType;
/// <summary> /// <summary>
/// 动态Type在使用 DbSet&lt;object&gt; 后使用本方法,指定实体类型 /// 动态Type在使用 DbSet&lt;object&gt; 后使用本方法,指定实体类型
/// </summary> /// </summary>
/// <param name="entityType"></param> /// <param name="entityType"></param>
/// <returns></returns> /// <returns></returns>
public void AsType(Type entityType) { public void AsType(Type entityType)
if (entityType == typeof(object)) throw new Exception("ISelect.AsType 参数不支持指定为 object"); {
if (entityType == _entityType) return; if (entityType == typeof(object)) throw new Exception("ISelect.AsType 参数不支持指定为 object");
var newtb = _fsql.CodeFirst.GetTableByEntity(entityType); if (entityType == _entityType) return;
_entityType = entityType; var newtb = _fsql.CodeFirst.GetTableByEntity(entityType);
_tablePriv = newtb ?? throw new Exception("DbSet.AsType 参数错误,请传入正确的实体类型"); _entityType = entityType;
_tableIdentitysPriv = null; _tablePriv = newtb ?? throw new Exception("DbSet.AsType 参数错误,请传入正确的实体类型");
} _tableIdentitysPriv = null;
}
public class EntityState { public class EntityState
public EntityState(TEntity value, string key) { {
this.Value = value; public EntityState(TEntity value, string key)
this.Key = key; {
this.Time = DateTime.Now; this.Value = value;
} this.Key = key;
public TEntity OldValue { get; set; } this.Time = DateTime.Now;
public TEntity Value { get; set; } }
public string Key { get; set; } public TEntity OldValue { get; set; }
public DateTime Time { get; set; } public TEntity Value { get; set; }
} public string Key { get; set; }
/// <summary> public DateTime Time { get; set; }
/// 附加实体,可用于不查询就更新或删除 }
/// </summary> /// <summary>
/// <param name="data"></param> /// 附加实体,可用于不查询就更新或删除
public void Attach(TEntity data) => AttachRange(new[] { data }); /// </summary>
public void AttachRange(IEnumerable<TEntity> data) { /// <param name="data"></param>
if (data == null || data.Any() == false) return; public void Attach(TEntity data) => AttachRange(new[] { data });
if (_table.Primarys.Any() == false) throw new Exception($"不可附加,实体没有主键:{_fsql.GetEntityString(_entityType, data.First())}"); public void AttachRange(IEnumerable<TEntity> data)
foreach (var item in data) { {
var key = _fsql.GetEntityKeyString(_entityType, item, false); if (data == null || data.Any() == false) return;
if (string.IsNullOrEmpty(key)) throw new Exception($"不可附加,未设置主键的值:{_fsql.GetEntityString(_entityType, item)}"); 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) => { _states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) =>
_fsql.MapEntityValue(_entityType, item, ov.Value); {
ov.Time = DateTime.Now; _fsql.MapEntityValue(_entityType, item, ov.Value);
return ov; ov.Time = DateTime.Now;
}); return ov;
} });
} }
/// <summary> }
/// 清空状态数据 /// <summary>
/// </summary> /// 清空状态数据
public void FlushState() { /// </summary>
_states.Clear(); public void FlushState()
} {
_states.Clear();
}
#region Utils #region Utils
EntityState CreateEntityState(TEntity data) { EntityState CreateEntityState(TEntity data)
if (data == null) throw new ArgumentNullException(nameof(data)); {
var key = _fsql.GetEntityKeyString(_entityType, data, false); if (data == null) throw new ArgumentNullException(nameof(data));
var state = new EntityState((TEntity)Activator.CreateInstance(_entityType), key); var key = _fsql.GetEntityKeyString(_entityType, data, false);
_fsql.MapEntityValue(_entityType, data, state.Value); var state = new EntityState((TEntity)Activator.CreateInstance(_entityType), key);
return state; _fsql.MapEntityValue(_entityType, data, state.Value);
} return state;
bool? ExistsInStates(TEntity data) { }
if (data == null) throw new ArgumentNullException(nameof(data)); bool? ExistsInStates(TEntity data)
var key = _fsql.GetEntityKeyString(_entityType, data, false); {
if (string.IsNullOrEmpty(key)) return null; if (data == null) throw new ArgumentNullException(nameof(data));
return _states.ContainsKey(key); var key = _fsql.GetEntityKeyString(_entityType, data, false);
} if (string.IsNullOrEmpty(key)) return null;
return _states.ContainsKey(key);
}
bool CanAdd(IEnumerable<TEntity> data, bool isThrow) { bool CanAdd(IEnumerable<TEntity> data, bool isThrow)
if (data == null) { {
if (isThrow) throw new ArgumentNullException(nameof(data)); if (data == null)
return false; {
} if (isThrow) throw new ArgumentNullException(nameof(data));
if (data.Any() == false) return false; return false;
foreach (var s in data) if (CanAdd(s, isThrow) == false) return false; }
return true; if (data.Any() == false) return false;
} foreach (var s in data) if (CanAdd(s, isThrow) == false) return false;
bool CanAdd(TEntity data, bool isThrow) { return true;
if (data == null) { }
if (isThrow) throw new ArgumentNullException(nameof(data)); bool CanAdd(TEntity data, bool isThrow)
return false; {
} if (data == null)
if (_table.Primarys.Any() == false) { {
if (isThrow) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}"); if (isThrow) throw new ArgumentNullException(nameof(data));
return false; return false;
} }
var key = _fsql.GetEntityKeyString(_entityType, data, true); if (_table.Primarys.Any() == false)
if (string.IsNullOrEmpty(key)) { {
switch (_fsql.Ado.DataType) { if (isThrow) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
case DataType.SqlServer: return false;
case DataType.PostgreSQL: }
return true; var key = _fsql.GetEntityKeyString(_entityType, data, true);
case DataType.MySql: if (string.IsNullOrEmpty(key))
case DataType.Oracle: {
case DataType.Sqlite: switch (_fsql.Ado.DataType)
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) { {
return true; case DataType.SqlServer:
} case DataType.PostgreSQL:
if (isThrow) throw new Exception($"不可添加,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); return true;
return false; case DataType.MySql:
} case DataType.Oracle:
} else { case DataType.Sqlite:
if (_states.ContainsKey(key)) { if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1)
if (isThrow) throw new Exception($"不可添加,已存在于状态管理:{_fsql.GetEntityString(_entityType, data)}"); {
return false; return true;
} }
var idval = _fsql.GetEntityIdentityValueWithPrimary(_entityType, data); if (isThrow) throw new Exception($"不可添加,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
if (idval > 0) { return false;
if (isThrow) throw new Exception($"不可添加,自增属性有值:{_fsql.GetEntityString(_entityType, data)}"); }
return false; }
} else
} {
return true; 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) { bool CanUpdate(IEnumerable<TEntity> data, bool isThrow)
if (data == null) { {
if (isThrow) throw new ArgumentNullException(nameof(data)); if (data == null)
return false; {
} if (isThrow) throw new ArgumentNullException(nameof(data));
if (data.Any() == false) return false; return false;
foreach (var s in data) if (CanUpdate(s, isThrow) == false) return false; }
return true; if (data.Any() == false) return false;
} foreach (var s in data) if (CanUpdate(s, isThrow) == false) return false;
bool CanUpdate(TEntity data, bool isThrow) { return true;
if (data == null) { }
if (isThrow) throw new ArgumentNullException(nameof(data)); bool CanUpdate(TEntity data, bool isThrow)
return false; {
} if (data == null)
if (_table.Primarys.Any() == false) { {
if (isThrow) throw new Exception($"不可更新,实体没有主键:{_fsql.GetEntityString(_entityType, data)}"); if (isThrow) throw new ArgumentNullException(nameof(data));
return false; return false;
} }
var key = _fsql.GetEntityKeyString(_entityType, data, false); if (_table.Primarys.Any() == false)
if (string.IsNullOrEmpty(key)) { {
if (isThrow) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); if (isThrow) throw new Exception($"不可更新,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
return false; return false;
} }
if (_states.TryGetValue(key, out var tryval) == false) { var key = _fsql.GetEntityKeyString(_entityType, data, false);
if (isThrow) throw new Exception($"不可更新,数据未被跟踪,应该先查询 或者 Attach{_fsql.GetEntityString(_entityType, data)}"); if (string.IsNullOrEmpty(key))
return false; {
} if (isThrow) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
return true; 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) { bool CanRemove(IEnumerable<TEntity> data, bool isThrow)
if (data == null) { {
if (isThrow) throw new ArgumentNullException(nameof(data)); if (data == null)
return false; {
} if (isThrow) throw new ArgumentNullException(nameof(data));
if (data.Any() == false) return false; return false;
foreach (var s in data) if (CanRemove(s, isThrow) == false) return false; }
return true; if (data.Any() == false) return false;
} foreach (var s in data) if (CanRemove(s, isThrow) == false) return false;
bool CanRemove(TEntity data, bool isThrow) { return true;
if (data == null) { }
if (isThrow) throw new ArgumentNullException(nameof(data)); bool CanRemove(TEntity data, bool isThrow)
return false; {
} if (data == null)
if (_table.Primarys.Any() == false) { {
if (isThrow) throw new Exception($"不可删除,实体没有主键:{_fsql.GetEntityString(_entityType, data)}"); if (isThrow) throw new ArgumentNullException(nameof(data));
return false; return false;
} }
var key = _fsql.GetEntityKeyString(_entityType, data, false); if (_table.Primarys.Any() == false)
if (string.IsNullOrEmpty(key)) { {
if (isThrow) throw new Exception($"不可删除,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); if (isThrow) throw new Exception($"不可删除,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
return false; return false;
} }
//if (_states.TryGetValue(key, out var tryval) == false) { var key = _fsql.GetEntityKeyString(_entityType, data, false);
// if (isThrow) throw new Exception($"不可删除,数据未被跟踪,应该先查询:{_fsql.GetEntityString(_entityType, data)}"); if (string.IsNullOrEmpty(key))
// return false; {
//} if (isThrow) throw new Exception($"不可删除,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
return true; return false;
} }
#endregion //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.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FreeSql { namespace FreeSql
partial class DbSet<TEntity> { {
partial class DbSet<TEntity>
{
Task DbContextExecCommandAsync() { Task DbContextExecCommandAsync()
_dicUpdateTimes.Clear(); {
return _ctx.ExecCommandAsync(); _dicUpdateTimes.Clear();
} return _ctx.ExecCommandAsync();
}
async Task<int> DbContextBetchAddAsync(EntityState[] adds) { async Task<int> DbContextBetchAddAsync(EntityState[] adds)
if (adds.Any() == false) return 0; {
var affrows = await this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrowsAsync(); if (adds.Any() == false) return 0;
return affrows; var affrows = await this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrowsAsync();
} return affrows;
}
#region Add #region Add
async Task AddPrivAsync(TEntity data, bool isCheck) { async Task AddPrivAsync(TEntity data, bool isCheck)
if (isCheck && CanAdd(data, true) == false) return; {
if (_tableIdentitys.Length > 0) { if (isCheck && CanAdd(data, true) == false) return;
//有自增,马上执行 if (_tableIdentitys.Length > 0)
switch (_fsql.Ado.DataType) { {
case DataType.SqlServer: //有自增,马上执行
case DataType.PostgreSQL: switch (_fsql.Ado.DataType)
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) { {
await DbContextExecCommandAsync(); case DataType.SqlServer:
var idtval = await this.OrmInsert(data).ExecuteIdentityAsync(); case DataType.PostgreSQL:
IncrAffrows(1); if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1)
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval); {
Attach(data); await DbContextExecCommandAsync();
if (_ctx.Options.EnableAddOrUpdateNavigateList) var idtval = await this.OrmInsert(data).ExecuteIdentityAsync();
await AddOrUpdateNavigateListAsync(data); IncrAffrows(1);
} else { _fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
await DbContextExecCommandAsync(); Attach(data);
var newval = (await this.OrmInsert(data).ExecuteInsertedAsync()).First(); if (_ctx.Options.EnableAddOrUpdateNavigateList)
IncrAffrows(1); await AddOrUpdateNavigateListAsync(data);
_fsql.MapEntityValue(_entityType, newval, data); }
Attach(newval); else
if (_ctx.Options.EnableAddOrUpdateNavigateList) {
await AddOrUpdateNavigateListAsync(data); await DbContextExecCommandAsync();
} var newval = (await this.OrmInsert(data).ExecuteInsertedAsync()).First();
return; IncrAffrows(1);
case DataType.MySql: _fsql.MapEntityValue(_entityType, newval, data);
case DataType.Oracle: Attach(newval);
case DataType.Sqlite: if (_ctx.Options.EnableAddOrUpdateNavigateList)
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) { await AddOrUpdateNavigateListAsync(data);
await DbContextExecCommandAsync(); }
var idtval = await this.OrmInsert(data).ExecuteIdentityAsync(); return;
IncrAffrows(1); case DataType.MySql:
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval); case DataType.Oracle:
Attach(data); case DataType.Sqlite:
if (_ctx.Options.EnableAddOrUpdateNavigateList) if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1)
await AddOrUpdateNavigateListAsync(data); {
} await DbContextExecCommandAsync();
return; var idtval = await this.OrmInsert(data).ExecuteIdentityAsync();
} IncrAffrows(1);
} _fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data)); Attach(data);
Attach(data); if (_ctx.Options.EnableAddOrUpdateNavigateList)
if (_ctx.Options.EnableAddOrUpdateNavigateList) await AddOrUpdateNavigateListAsync(data);
await AddOrUpdateNavigateListAsync(data); }
} return;
public Task AddAsync(TEntity data) => AddPrivAsync(data, true); }
async public Task AddRangeAsync(IEnumerable<TEntity> data) { }
if (CanAdd(data, true) == false) return; EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data));
if (data.ElementAtOrDefault(1) == default(TEntity)) { Attach(data);
await AddAsync(data.First()); if (_ctx.Options.EnableAddOrUpdateNavigateList)
return; await AddOrUpdateNavigateListAsync(data);
} }
if (_tableIdentitys.Length > 0) { public Task AddAsync(TEntity data) => AddPrivAsync(data, true);
//有自增,马上执行 async public Task AddRangeAsync(IEnumerable<TEntity> data)
switch (_fsql.Ado.DataType) { {
case DataType.SqlServer: if (CanAdd(data, true) == false) return;
case DataType.PostgreSQL: if (data.ElementAtOrDefault(1) == default(TEntity))
await DbContextExecCommandAsync(); {
var rets = await this.OrmInsert(data).ExecuteInsertedAsync(); await AddAsync(data.First());
if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配"); return;
var idx = 0; }
foreach (var s in data) if (_tableIdentitys.Length > 0)
_fsql.MapEntityValue(_entityType, rets[idx++], s); {
IncrAffrows(rets.Count); //有自增,马上执行
AttachRange(rets); switch (_fsql.Ado.DataType)
if (_ctx.Options.EnableAddOrUpdateNavigateList) {
foreach (var item in data) case DataType.SqlServer:
await AddOrUpdateNavigateListAsync(item); case DataType.PostgreSQL:
return; await DbContextExecCommandAsync();
case DataType.MySql: var rets = await this.OrmInsert(data).ExecuteInsertedAsync();
case DataType.Oracle: if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配");
case DataType.Sqlite: var idx = 0;
foreach (var s in data) foreach (var s in data)
await AddPrivAsync(s, false); _fsql.MapEntityValue(_entityType, rets[idx++], s);
return; IncrAffrows(rets.Count);
} AttachRange(rets);
} else { if (_ctx.Options.EnableAddOrUpdateNavigateList)
//进入队列,等待 SaveChanges 时执行 foreach (var item in data)
foreach (var item in data) await AddOrUpdateNavigateListAsync(item);
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(item)); return;
AttachRange(data); case DataType.MySql:
if (_ctx.Options.EnableAddOrUpdateNavigateList) case DataType.Oracle:
foreach (var item in data) case DataType.Sqlite:
await AddOrUpdateNavigateListAsync(item); foreach (var s in data)
} await AddPrivAsync(s, false);
} return;
async Task AddOrUpdateNavigateListAsync(TEntity item) { }
Type itemType = null; }
foreach (var prop in _table.Properties) { else
if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue; {
if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue; //进入队列,等待 SaveChanges 时执行
var tref = _table.GetTableRef(prop.Key, true); foreach (var item in data)
if (tref == null) continue; 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) { switch (tref.RefType)
case Internal.Model.TableRefType.OneToOne: {
case Internal.Model.TableRefType.ManyToOne: case Internal.Model.TableRefType.OneToOne:
case Internal.Model.TableRefType.ManyToMany: case Internal.Model.TableRefType.ManyToOne:
continue; case Internal.Model.TableRefType.ManyToMany:
case Internal.Model.TableRefType.OneToMany: continue;
if (itemType == null) itemType = item.GetType(); case Internal.Model.TableRefType.OneToMany:
if (_table.TypeLazy != null && itemType == _table.TypeLazy) { if (itemType == null) itemType = item.GetType();
var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, System.Reflection.FieldInfo>()).GetOrAdd(prop.Key, propName => if (_table.TypeLazy != null && itemType == _table.TypeLazy)
_table.TypeLazy.GetField($"__lazy__{propName}", System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)); {
if (lazyField != null) { var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, System.Reflection.FieldInfo>()).GetOrAdd(prop.Key, propName =>
var lazyFieldValue = (bool)lazyField.GetValue(item); _table.TypeLazy.GetField($"__lazy__{propName}", System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance));
if (lazyFieldValue == false) continue; if (lazyField != null)
} {
} var lazyFieldValue = (bool)lazyField.GetValue(item);
var propVal = prop.Value.GetValue(item); if (lazyFieldValue == false) continue;
var propValEach = propVal as IEnumerable; }
if (propValEach == null) continue; }
object dbset = null; var propVal = prop.Value.GetValue(item);
System.Reflection.MethodInfo dbsetAddOrUpdate = null; var propValEach = propVal as IEnumerable;
foreach (var propValItem in propValEach) { if (propValEach == null) continue;
if (dbset == null) { object dbset = null;
dbset = _ctx.Set(tref.RefEntityType); System.Reflection.MethodInfo dbsetAddOrUpdate = null;
dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdateAsync", new Type[] { tref.RefEntityType }); foreach (var propValItem in propValEach)
} {
for (var colidx = 0; colidx < tref.Columns.Count; colidx++) { if (dbset == null)
tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName] {
.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item)); dbset = _ctx.Set(tref.RefEntityType);
} dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdateAsync", new Type[] { tref.RefEntityType });
Task task = dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem }) as Task; }
await task; for (var colidx = 0; colidx < tref.Columns.Count; colidx++)
} {
break; 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;
#endregion await task;
}
break;
}
}
}
#endregion
#region UpdateAsync #region UpdateAsync
Task<int> DbContextBetchUpdateAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, false); Task<int> DbContextBetchUpdateAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, false);
Task<int> DbContextBetchUpdateNowAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, true); Task<int> DbContextBetchUpdateNowAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, true);
async Task<int> DbContextBetchUpdatePrivAsync(EntityState[] ups, bool isLiveUpdate) { async Task<int> DbContextBetchUpdatePrivAsync(EntityState[] ups, bool isLiveUpdate)
if (ups.Any() == false) return 0; {
var uplst1 = ups[ups.Length - 1]; if (ups.Any() == false) return 0;
var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null; 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; if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
var lstval2 = default(EntityState); var lstval2 = default(EntityState);
if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEntityString(_entityType, uplst2.Value)}"); 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 cuig1 = _fsql.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true);
var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null; var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null;
List<EntityState> data = null; List<EntityState> data = null;
string[] cuig = null; string[] cuig = null;
if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) { if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0)
//最后一个不保存 {
data = ups.ToList(); //最后一个不保存
data.RemoveAt(ups.Length - 1); data = ups.ToList();
cuig = cuig2; data.RemoveAt(ups.Length - 1);
} else if (isLiveUpdate) { cuig = cuig2;
//立即保存 }
data = ups.ToList(); else if (isLiveUpdate)
cuig = cuig1; {
} //立即保存
data = ups.ToList();
cuig = cuig1;
}
if (data?.Count > 0) { if (data?.Count > 0)
{
if (cuig.Length == _table.Columns.Count) if (cuig.Length == _table.Columns.Count)
return ups.Length == data.Count ? -998 : -997; return ups.Length == data.Count ? -998 : -997;
var updateSource = data.Select(a => a.Value).ToArray(); var updateSource = data.Select(a => a.Value).ToArray();
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig); var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
var affrows = await update.ExecuteAffrowsAsync(); var affrows = await update.ExecuteAffrowsAsync();
foreach (var newval in data) { foreach (var newval in data)
if (_states.TryGetValue(newval.Key, out var tryold)) {
_fsql.MapEntityValue(_entityType, newval.Value, tryold.Value); if (_states.TryGetValue(newval.Key, out var tryold))
if (newval.OldValue != null) _fsql.MapEntityValue(_entityType, newval.Value, tryold.Value);
_fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue); if (newval.OldValue != null)
} _fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue);
return affrows; }
} return affrows;
}
//等待下次对比再保存 //等待下次对比再保存
return 0; return 0;
} }
async public Task UpdateAsync(TEntity data) { async public Task UpdateAsync(TEntity data)
var exists = ExistsInStates(data); {
if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); var exists = ExistsInStates(data);
if (exists == false) { if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
var olddata = await OrmSelect(data).FirstAsync(); if (exists == false)
if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}"); {
} var olddata = await OrmSelect(data).FirstAsync();
if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}");
}
await UpdateRangePrivAsync(new[] { data }, true); await UpdateRangePrivAsync(new[] { data }, true);
} }
public Task UpdateRangeAsync(IEnumerable<TEntity> data) => UpdateRangePrivAsync(data, true); public Task UpdateRangeAsync(IEnumerable<TEntity> data) => UpdateRangePrivAsync(data, true);
async Task UpdateRangePrivAsync(IEnumerable<TEntity> data, bool isCheck) { async Task UpdateRangePrivAsync(IEnumerable<TEntity> data, bool isCheck)
if (CanUpdate(data, true) == false) return; {
foreach (var item in data) { if (CanUpdate(data, true) == false) return;
if (_dicUpdateTimes.ContainsKey(item)) foreach (var item in data)
await DbContextExecCommandAsync(); {
_dicUpdateTimes.Add(item, 1); if (_dicUpdateTimes.ContainsKey(item))
await DbContextExecCommandAsync();
_dicUpdateTimes.Add(item, 1);
var state = CreateEntityState(item); var state = CreateEntityState(item);
state.OldValue = item; state.OldValue = item;
EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state); EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state);
} }
if (_ctx.Options.EnableAddOrUpdateNavigateList) if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data) foreach (var item in data)
await AddOrUpdateNavigateListAsync(item); await AddOrUpdateNavigateListAsync(item);
} }
#endregion #endregion
#region RemoveAsync #region RemoveAsync
async Task<int> DbContextBetchRemoveAsync(EntityState[] dels) { async Task<int> DbContextBetchRemoveAsync(EntityState[] dels)
if (dels.Any() == false) return 0; {
var affrows = await this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrowsAsync(); if (dels.Any() == false) return 0;
return Math.Max(dels.Length, affrows); var affrows = await this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrowsAsync();
} return Math.Max(dels.Length, affrows);
#endregion }
#endregion
#region AddOrUpdateAsync #region AddOrUpdateAsync
async public Task AddOrUpdateAsync(TEntity data) { 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)}"); if (data == null) throw new ArgumentNullException(nameof(data));
if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
var flagExists = ExistsInStates(data); var flagExists = ExistsInStates(data);
if (flagExists == false) { if (flagExists == false)
var olddata = await OrmSelect(data).FirstAsync(); {
if (olddata == null) flagExists = false; var olddata = await OrmSelect(data).FirstAsync();
} if (olddata == null) flagExists = false;
}
if (flagExists == true && CanUpdate(data, false)) { if (flagExists == true && CanUpdate(data, false))
await DbContextExecCommandAsync(); {
var affrows = _ctx._affrows; await DbContextExecCommandAsync();
await UpdateRangePrivAsync(new[] { data }, false); var affrows = _ctx._affrows;
await DbContextExecCommandAsync(); await UpdateRangePrivAsync(new[] { data }, false);
affrows = _ctx._affrows - affrows; await DbContextExecCommandAsync();
if (affrows > 0) return; affrows = _ctx._affrows - affrows;
} if (affrows > 0) return;
if (CanAdd(data, false)) { }
_fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data); if (CanAdd(data, false))
await AddPrivAsync(data, false); {
} _fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data);
} await AddPrivAsync(data, false);
#endregion }
} }
#endregion
}
} }

View File

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

View File

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

View File

@ -2,37 +2,41 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
public static class FreeSqlDbContextExtenssions { public static class FreeSqlDbContextExtenssions
{
/// <summary> /// <summary>
/// 创建普通数据上下文档对象 /// 创建普通数据上下文档对象
/// </summary> /// </summary>
/// <param name="that"></param> /// <param name="that"></param>
/// <returns></returns> /// <returns></returns>
public static DbContext CreateDbContext(this IFreeSql that) { public static DbContext CreateDbContext(this IFreeSql that)
return new FreeContext(that); {
} return new FreeContext(that);
}
/// <summary> /// <summary>
/// 不跟踪查询的实体数据(在不需要更新其数据时使用),可提长查询性能 /// 不跟踪查询的实体数据(在不需要更新其数据时使用),可提长查询性能
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="select"></param> /// <param name="select"></param>
/// <returns></returns> /// <returns></returns>
public static ISelect<T> NoTracking<T>(this ISelect<T> select) where T : class { public static ISelect<T> NoTracking<T>(this ISelect<T> select) where T : class
return select.TrackToList(null); {
} return select.TrackToList(null);
}
/// <summary> /// <summary>
/// 设置 DbContext 选项设置 /// 设置 DbContext 选项设置
/// </summary> /// </summary>
/// <param name="that"></param> /// <param name="that"></param>
/// <param name="options"></param> /// <param name="options"></param>
public static void SetDbContextOptions(this IFreeSql that, Action<DbContextOptions> options) { public static void SetDbContextOptions(this IFreeSql that, Action<DbContextOptions> options)
if (options == null) return; {
var cfg = _dicSetDbContextOptions.GetOrAdd(that, t => new DbContextOptions()); if (options == null) return;
options(cfg); var cfg = _dicSetDbContextOptions.GetOrAdd(that, t => new DbContextOptions());
_dicSetDbContextOptions.AddOrUpdate(that, cfg, (t, o) => cfg); options(cfg);
} _dicSetDbContextOptions.AddOrUpdate(that, cfg, (t, o) => cfg);
internal static ConcurrentDictionary<IFreeSql, DbContextOptions> _dicSetDbContextOptions = new ConcurrentDictionary<IFreeSql, DbContextOptions>(); }
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.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FreeSql { namespace FreeSql
internal class RepositoryDbContext : DbContext { {
internal class RepositoryDbContext : DbContext
{
protected IBaseRepository _repos; protected IBaseRepository _repos;
public RepositoryDbContext(IFreeSql orm, IBaseRepository repos) : base() { public RepositoryDbContext(IFreeSql orm, IBaseRepository repos) : base()
_orm = orm; {
_repos = repos; _orm = orm;
_isUseUnitOfWork = false; _repos = repos;
_uowPriv = _repos.UnitOfWork; _isUseUnitOfWork = false;
} _uowPriv = _repos.UnitOfWork;
}
static ConcurrentDictionary<Type, FieldInfo> _dicGetRepositoryDbField = new ConcurrentDictionary<Type, FieldInfo>(); 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)); 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) { public override IDbSet Set(Type entityType)
if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType]; {
if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType];
var tb = _orm.CodeFirst.GetTableByEntity(entityType); var tb = _orm.CodeFirst.GetTableByEntity(entityType);
if (tb == null) return null; if (tb == null) return null;
object repos = _repos; object repos = _repos;
if (entityType != _repos.EntityType) { if (entityType != _repos.EntityType)
repos = Activator.CreateInstance(typeof(DefaultRepository<,>).MakeGenericType(entityType, typeof(int)), _repos.Orm); {
(repos as IBaseRepository).UnitOfWork = _repos.UnitOfWork; repos = Activator.CreateInstance(typeof(DefaultRepository<,>).MakeGenericType(entityType, typeof(int)), _repos.Orm);
GetRepositoryDbField(entityType).SetValue(repos, this); (repos as IBaseRepository).UnitOfWork = _repos.UnitOfWork;
GetRepositoryDbField(entityType).SetValue(repos, this);
typeof(RepositoryDbContext).GetMethod("SetRepositoryDataFilter").MakeGenericMethod(_repos.EntityType) typeof(RepositoryDbContext).GetMethod("SetRepositoryDataFilter").MakeGenericMethod(_repos.EntityType)
.Invoke(null, new object[] { repos, _repos }); .Invoke(null, new object[] { repos, _repos });
} }
var sd = Activator.CreateInstance(typeof(RepositoryDbSet<>).MakeGenericType(entityType), repos) as IDbSet; var sd = Activator.CreateInstance(typeof(RepositoryDbSet<>).MakeGenericType(entityType), repos) as IDbSet;
if (entityType != typeof(object)) _dicSet.Add(entityType, sd); if (entityType != typeof(object)) _dicSet.Add(entityType, sd);
return sd; return sd;
} }
public static void SetRepositoryDataFilter<TEntity>(object repos, BaseRepository<TEntity> baseRepo) where TEntity : class { public static void SetRepositoryDataFilter<TEntity>(object repos, BaseRepository<TEntity> baseRepo) where TEntity : class
var filter = baseRepo.DataFilter as DataFilter<TEntity>; {
DataFilterUtil.SetRepositoryDataFilter(repos, fl => { var filter = baseRepo.DataFilter as DataFilter<TEntity>;
foreach (var f in filter._filters) DataFilterUtil.SetRepositoryDataFilter(repos, fl =>
fl.Apply<TEntity>(f.Key, f.Value.Expression); {
}); foreach (var f in filter._filters)
} fl.Apply<TEntity>(f.Key, f.Value.Expression);
});
}
public override int SaveChanges() { public override int SaveChanges()
ExecCommand(); {
var ret = _affrows; ExecCommand();
_affrows = 0; var ret = _affrows;
return ret; _affrows = 0;
} return ret;
async public override Task<int> SaveChangesAsync() { }
await ExecCommandAsync(); async public override Task<int> SaveChangesAsync()
var ret = _affrows; {
_affrows = 0; await ExecCommandAsync();
return ret; var ret = _affrows;
} _affrows = 0;
} return ret;
}
}
} }

View File

@ -3,58 +3,67 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
namespace FreeSql { namespace FreeSql
internal class RepositoryDbSet<TEntity> : DbSet<TEntity> where TEntity : class { {
internal class RepositoryDbSet<TEntity> : DbSet<TEntity> where TEntity : class
{
protected BaseRepository<TEntity> _repos; protected BaseRepository<TEntity> _repos;
public RepositoryDbSet(BaseRepository<TEntity> repos) { public RepositoryDbSet(BaseRepository<TEntity> repos)
_ctx = repos._db; {
_fsql = repos.Orm; _ctx = repos._db;
_uow = repos.UnitOfWork; _fsql = repos.Orm;
_repos = repos; _uow = repos.UnitOfWork;
} _repos = repos;
}
protected override ISelect<TEntity> OrmSelect(object dywhere) { protected override ISelect<TEntity> OrmSelect(object dywhere)
var select = base.OrmSelect(dywhere); {
var select = base.OrmSelect(dywhere);
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true); var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
foreach (var filter in filters) select.Where(filter.Value.Expression); foreach (var filter in filters) select.Where(filter.Value.Expression);
return select.AsTable(_repos.AsTableSelectInternal); return select.AsTable(_repos.AsTableSelectInternal);
} }
internal ISelect<TEntity> OrmSelectInternal(object dywhere) => OrmSelect(dywhere); internal ISelect<TEntity> OrmSelectInternal(object dywhere) => OrmSelect(dywhere);
protected override IUpdate<TEntity> OrmUpdate(IEnumerable<TEntity> entitys) { 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); var update = base.OrmUpdate(entitys);
foreach (var filter in filters) { var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
if (entitys != null) foreach (var filter in filters)
foreach (var entity in entitys) {
if (filter.Value.ExpressionDelegate?.Invoke(entity) == false) if (entitys != null)
throw new Exception($"FreeSql.Repository Update 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},更新的数据不符合 {_fsql.GetEntityString(_entityType, entity)}"); foreach (var entity in entitys)
update.Where(filter.Value.Expression); if (filter.Value.ExpressionDelegate?.Invoke(entity) == false)
} throw new Exception($"FreeSql.Repository Update 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},更新的数据不符合 {_fsql.GetEntityString(_entityType, entity)}");
return update.AsTable(_repos.AsTableInternal); update.Where(filter.Value.Expression);
} }
internal IUpdate<TEntity> OrmUpdateInternal(IEnumerable<TEntity> entitys) => OrmUpdate(entitys); return update.AsTable(_repos.AsTableInternal);
protected override IDelete<TEntity> OrmDelete(object dywhere) { }
var delete = base.OrmDelete(dywhere); internal IUpdate<TEntity> OrmUpdateInternal(IEnumerable<TEntity> entitys) => OrmUpdate(entitys);
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true); protected override IDelete<TEntity> OrmDelete(object dywhere)
foreach (var filter in filters) delete.Where(filter.Value.Expression); {
return delete.AsTable(_repos.AsTableInternal); var delete = base.OrmDelete(dywhere);
} var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
internal IDelete<TEntity> OrmDeleteInternal(object dywhere) => OrmDelete(dywhere); foreach (var filter in filters) delete.Where(filter.Value.Expression);
protected override IInsert<TEntity> OrmInsert(TEntity entity) => OrmInsert(new[] { entity }); return delete.AsTable(_repos.AsTableInternal);
protected override IInsert<TEntity> OrmInsert(IEnumerable<TEntity> entitys) { }
var insert = base.OrmInsert(entitys); internal IDelete<TEntity> OrmDeleteInternal(object dywhere) => OrmDelete(dywhere);
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true); protected override IInsert<TEntity> OrmInsert(TEntity entity) => OrmInsert(new[] { entity });
foreach (var filter in filters) { protected override IInsert<TEntity> OrmInsert(IEnumerable<TEntity> entitys)
if (entitys != null) {
foreach (var entity in entitys) var insert = base.OrmInsert(entitys);
if (filter.Value.ExpressionDelegate?.Invoke(entity) == false) var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
throw new Exception($"FreeSql.Repository Insert 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},插入的数据不符合 {_fsql.GetEntityString(_entityType, entity)}"); foreach (var filter in filters)
} {
return insert.AsTable(_repos.AsTableInternal); if (entitys != null)
} foreach (var entity in entitys)
internal IInsert<TEntity> OrmInsertInternal(TEntity entity) => OrmInsert(entity); if (filter.Value.ExpressionDelegate?.Invoke(entity) == false)
internal IInsert<TEntity> OrmInsertInternal(IEnumerable<TEntity> entitys) => OrmInsert(entitys); 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;
using System.Linq.Expressions; using System.Linq.Expressions;
namespace FreeSql { namespace FreeSql
{
public interface IRepositoryUnitOfWork : IUnitOfWork { public interface IRepositoryUnitOfWork : IUnitOfWork
/// <summary> {
/// 在工作单元内创建默认仓库类,工作单元下的仓储操作具有事务特点 /// <summary>
/// </summary> /// 在工作单元内创建默认仓库类,工作单元下的仓储操作具有事务特点
/// <typeparam name="TEntity"></typeparam> /// </summary>
/// <typeparam name="TKey"></typeparam> /// <typeparam name="TEntity"></typeparam>
/// <param name="filter">数据过滤 + 验证</param> /// <typeparam name="TKey"></typeparam>
/// <returns></returns> /// <param name="filter">数据过滤 + 验证</param>
DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class; /// <returns></returns>
DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class;
/// <summary> /// <summary>
/// 在工作单元内创建联合主键的仓储类,工作单元下的仓储操作具有事务特点 /// 在工作单元内创建联合主键的仓储类,工作单元下的仓储操作具有事务特点
/// </summary> /// </summary>
/// <typeparam name="TEntity"></typeparam> /// <typeparam name="TEntity"></typeparam>
/// <param name="filter">数据过滤 + 验证</param> /// <param name="filter">数据过滤 + 验证</param>
/// <returns></returns> /// <returns></returns>
BaseRepository<TEntity> GetRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class; BaseRepository<TEntity> GetRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class;
/// <summary> /// <summary>
/// 在工作单元内创建仓库类,工作单元下的仓储操作具有事务特点 /// 在工作单元内创建仓库类,工作单元下的仓储操作具有事务特点
/// </summary> /// </summary>
/// <typeparam name="TEntity"></typeparam> /// <typeparam name="TEntity"></typeparam>
/// <param name="filter">数据过滤 + 验证</param> /// <param name="filter">数据过滤 + 验证</param>
/// <param name="asTable">分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository</param> /// <param name="asTable">分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository</param>
/// <returns></returns> /// <returns></returns>
GuidRepository<TEntity> GetGuidRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null, Func<string, string> asTable = null) where TEntity : class; 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 { 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; var repos = new GuidRepository<TEntity>(_fsql, filter, asTable);
return repos; repos.UnitOfWork = this;
} return repos;
}
public DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class { 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; var repos = new DefaultRepository<TEntity, TKey>(_fsql, filter);
return repos; repos.UnitOfWork = this;
} return repos;
}
public BaseRepository<TEntity> GetRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class { 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; var repos = new DefaultRepository<TEntity, int>(_fsql, filter);
return repos; repos.UnitOfWork = this;
} return repos;
} }
}
} }

View File

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

View File

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

View File

@ -5,35 +5,41 @@ using System.Reflection;
using System.Linq; using System.Linq;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
namespace FreeSql { namespace FreeSql
public static class FreeSqlRepositoryDependencyInjection { {
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(IReadOnlyRepository<>), typeof(GuidRepository<>));
services.AddScoped(typeof(IBasicRepository<>), typeof(GuidRepository<>)); services.AddScoped(typeof(IBasicRepository<>), typeof(GuidRepository<>));
services.AddScoped(typeof(BaseRepository<>), typeof(GuidRepository<>)); services.AddScoped(typeof(BaseRepository<>), typeof(GuidRepository<>));
services.AddScoped(typeof(GuidRepository<>)); services.AddScoped(typeof(GuidRepository<>));
services.AddScoped(typeof(IReadOnlyRepository<,>), typeof(DefaultRepository<,>)); services.AddScoped(typeof(IReadOnlyRepository<,>), typeof(DefaultRepository<,>));
services.AddScoped(typeof(IBasicRepository<,>), typeof(DefaultRepository<,>)); services.AddScoped(typeof(IBasicRepository<,>), typeof(DefaultRepository<,>));
services.AddScoped(typeof(BaseRepository<,>), typeof(DefaultRepository<,>)); services.AddScoped(typeof(BaseRepository<,>), typeof(DefaultRepository<,>));
services.AddScoped(typeof(DefaultRepository<,>)); services.AddScoped(typeof(DefaultRepository<,>));
if (assemblies?.Any() == true) { if (assemblies?.Any() == true)
foreach(var asse in assemblies) { {
foreach (var repos in asse.GetTypes().Where(a => a.IsAbstract == false && typeof(IBaseRepository).IsAssignableFrom(a))) { 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 #endif

View File

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

View File

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

View File

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

View File

@ -1,45 +1,48 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FreeSql { namespace FreeSql
public interface IBasicRepository<TEntity> : IReadOnlyRepository<TEntity> {
where TEntity : class { public interface IBasicRepository<TEntity> : IReadOnlyRepository<TEntity>
TEntity Insert(TEntity entity); where TEntity : class
List<TEntity> Insert(IEnumerable<TEntity> entitys); {
Task<TEntity> InsertAsync(TEntity entity); TEntity Insert(TEntity entity);
Task<List<TEntity>> InsertAsync(IEnumerable<TEntity> entitys); List<TEntity> Insert(IEnumerable<TEntity> entitys);
Task<TEntity> InsertAsync(TEntity entity);
Task<List<TEntity>> InsertAsync(IEnumerable<TEntity> entitys);
/// <summary> /// <summary>
/// 清空状态数据 /// 清空状态数据
/// </summary> /// </summary>
void FlushState(); void FlushState();
/// <summary> /// <summary>
/// 附加实体,可用于不查询就更新或删除 /// 附加实体,可用于不查询就更新或删除
/// </summary> /// </summary>
/// <param name="entity"></param> /// <param name="entity"></param>
void Attach(TEntity entity); void Attach(TEntity entity);
void Attach(IEnumerable<TEntity> entity); void Attach(IEnumerable<TEntity> entity);
int Update(TEntity entity); int Update(TEntity entity);
int Update(IEnumerable<TEntity> entitys); int Update(IEnumerable<TEntity> entitys);
Task<int> UpdateAsync(TEntity entity); Task<int> UpdateAsync(TEntity entity);
Task<int> UpdateAsync(IEnumerable<TEntity> entitys); Task<int> UpdateAsync(IEnumerable<TEntity> entitys);
TEntity InsertOrUpdate(TEntity entity); TEntity InsertOrUpdate(TEntity entity);
Task<TEntity> InsertOrUpdateAsync(TEntity entity); Task<TEntity> InsertOrUpdateAsync(TEntity entity);
IUpdate<TEntity> UpdateDiy { get; } IUpdate<TEntity> UpdateDiy { get; }
int Delete(TEntity entity); int Delete(TEntity entity);
int Delete(IEnumerable<TEntity> entitys); int Delete(IEnumerable<TEntity> entitys);
Task<int> DeleteAsync(TEntity entity); Task<int> DeleteAsync(TEntity entity);
Task<int> DeleteAsync(IEnumerable<TEntity> entitys); Task<int> DeleteAsync(IEnumerable<TEntity> entitys);
} }
public interface IBasicRepository<TEntity, TKey> : IBasicRepository<TEntity>, IReadOnlyRepository<TEntity, TKey> public interface IBasicRepository<TEntity, TKey> : IBasicRepository<TEntity>, IReadOnlyRepository<TEntity, TKey>
where TEntity : class { where TEntity : class
int Delete(TKey id); {
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.Linq.Expressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FreeSql { namespace FreeSql
public interface IReadOnlyRepository<TEntity> : IBaseRepository {
where TEntity : class { 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> Where(Expression<Func<TEntity, bool>> exp);
ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp); ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp);
} }
public interface IReadOnlyRepository<TEntity, TKey> : IReadOnlyRepository<TEntity> public interface IReadOnlyRepository<TEntity, TKey> : IReadOnlyRepository<TEntity>
where TEntity : class { where TEntity : class
TEntity Get(TKey id); {
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 { namespace FreeSql.Extensions.EntityUtil
public static class TempExtensions { {
} public static class TempExtensions
{
}
} }

View File

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

View File

@ -3,22 +3,26 @@ using System;
using System.Data; using System.Data;
using System.Data.Common; using System.Data.Common;
namespace FreeSql { namespace FreeSql
class UnitOfWork : IUnitOfWork { {
class UnitOfWork : IUnitOfWork
{
protected IFreeSql _fsql; protected IFreeSql _fsql;
protected Object<DbConnection> _conn; protected Object<DbConnection> _conn;
protected DbTransaction _tran; protected DbTransaction _tran;
public UnitOfWork(IFreeSql fsql) { public UnitOfWork(IFreeSql fsql)
_fsql = fsql; {
} _fsql = fsql;
}
void ReturnObject() { void ReturnObject()
_fsql.Ado.MasterPool.Return(_conn); {
_tran = null; _fsql.Ado.MasterPool.Return(_conn);
_conn = null; _tran = null;
} _conn = null;
}
/// <summary> /// <summary>
@ -49,55 +53,74 @@ namespace FreeSql {
public IsolationLevel? IsolationLevel { get; set; } public IsolationLevel? IsolationLevel { get; set; }
public DbTransaction GetOrBeginTransaction(bool isCreate = true) { public DbTransaction GetOrBeginTransaction(bool isCreate = true)
{
if (_tran != null) return _tran; if (_tran != null) return _tran;
if (isCreate == false) return null; if (isCreate == false) return null;
if (!Enable) 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(); _conn = _fsql.Ado.MasterPool.Get();
try { try
_tran = IsolationLevel == null ? {
_conn.Value.BeginTransaction() : _tran = IsolationLevel == null ?
_conn.Value.BeginTransaction(IsolationLevel.Value); _conn.Value.BeginTransaction() :
} catch { _conn.Value.BeginTransaction(IsolationLevel.Value);
ReturnObject(); }
throw; catch
} {
return _tran; ReturnObject();
} throw;
}
return _tran;
}
public void Commit() { public void Commit()
if (_tran != null) { {
try { if (_tran != null)
_tran.Commit(); {
} finally { try
ReturnObject(); {
} _tran.Commit();
} }
} finally
public void Rollback() { {
if (_tran != null) { ReturnObject();
try { }
_tran.Rollback(); }
} finally { }
ReturnObject(); public void Rollback()
} {
} if (_tran != null)
} {
~UnitOfWork() { try
this.Dispose(); {
} _tran.Rollback();
bool _isdisposed = false; }
public void Dispose() { finally
if (_isdisposed) return; {
try { ReturnObject();
this.Rollback(); }
} finally { }
_isdisposed = true; }
GC.SuppressFinalize(this); ~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 System;
using Xunit; using Xunit;
namespace FreeSql.Tests { namespace FreeSql.Tests
public class RepositoryTests { {
public class RepositoryTests
{
[Fact] [Fact]
public void AddUpdate() { public void AddUpdate()
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>(); {
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();
var item = repos.Insert(new AddUpdateInfo()); var item = repos.Insert(new AddUpdateInfo());
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
item = repos.Insert(new AddUpdateInfo { Id = Guid.NewGuid() }); item = repos.Insert(new AddUpdateInfo { Id = Guid.NewGuid() });
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
item.Title = "xxx"; item.Title = "xxx";
repos.Update(item); repos.Update(item);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
Console.WriteLine(repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ToSql()); 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(); repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ExecuteAffrows();
item = repos.Find(item.Id); item = repos.Find(item.Id);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
} }
[Fact] [Fact]
public void UpdateAttach() { public void UpdateAttach()
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>(); {
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();
var item = new AddUpdateInfo { Id = Guid.NewGuid() }; var item = new AddUpdateInfo { Id = Guid.NewGuid() };
repos.Attach(item); repos.Attach(item);
item.Title = "xxx"; item.Title = "xxx";
repos.Update(item); repos.Update(item);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
Console.WriteLine(repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ToSql()); 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(); repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ExecuteAffrows();
item = repos.Find(item.Id); item = repos.Find(item.Id);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
} }
[Fact] [Fact]
public void UpdateWhenNotExists() { public void UpdateWhenNotExists()
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>(); {
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();
var item = new AddUpdateInfo { Id = Guid.NewGuid() }; var item = new AddUpdateInfo { Id = Guid.NewGuid() };
item.Title = "xxx"; item.Title = "xxx";
Assert.Throws<Exception>(() => repos.Update(item)); Assert.Throws<Exception>(() => repos.Update(item));
} }
[Fact] [Fact]
public void Update() { public void Update()
g.sqlite.Insert(new AddUpdateInfo()).ExecuteAffrows(); {
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"; item.Title = "xxx";
repos.Update(item); repos.Update(item);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
} }
public class AddUpdateInfo { public class AddUpdateInfo
{
public Guid Id { get; set; } public Guid Id { get; set; }
public string Title { get; set; } public string Title { get; set; }
public int Clicks { get; set; } = 10; public int Clicks { get; set; } = 10;
} }
[Fact] [Fact]
public void UnitOfWorkRepository() { public void UnitOfWorkRepository()
foreach (var fsql in new[] { g.sqlite, /*g.mysql, g.pgsql, g.oracle, g.sqlserver*/ }) { {
foreach (var fsql in new[] { g.sqlite, /*g.mysql, g.pgsql, g.oracle, g.sqlserver*/ })
{
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.UserId).IsPrimary(true);
f.Property(b => b.Name).IsNullable(false); f.Property(b => b.Id).IsPrimary(true).IsIdentity(true);
}); f.Property(b => b.Name).IsNullable(false);
});
FlowModel flow = new FlowModel() { FlowModel flow = new FlowModel()
CreateTime = DateTime.Now, {
Name = "aaa", CreateTime = DateTime.Now,
LastModifyTime = DateTime.Now, Name = "aaa",
UserId = 1, LastModifyTime = DateTime.Now,
}; UserId = 1,
var flowRepos = fsql.GetRepository<FlowModel>(); };
flowRepos.Insert(flow); var flowRepos = fsql.GetRepository<FlowModel>();
flowRepos.Insert(flow);
//ÊÂÎñÌí¼Ó //ÊÂÎñÌí¼Ó
flow = new FlowModel() { flow = new FlowModel()
CreateTime = DateTime.Now, {
Name = "aaa", CreateTime = DateTime.Now,
LastModifyTime = DateTime.Now, Name = "aaa",
UserId = 1, LastModifyTime = DateTime.Now,
}; UserId = 1,
using (var uow = fsql.CreateUnitOfWork()) { };
flowRepos = uow.GetRepository<FlowModel>(); using (var uow = fsql.CreateUnitOfWork())
flowRepos.Insert(flow); {
uow.Commit(); flowRepos = uow.GetRepository<FlowModel>();
} flowRepos.Insert(flow);
uow.Commit();
}
} }
} }
[Fact] [Fact]
public void UnitOfWorkRepositoryWithDisableBeforeInsert() 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.UserId).IsPrimary(true);
f.Property(b => b.Id).IsPrimary(true).IsIdentity(true); f.Property(b => b.Id).IsPrimary(true).IsIdentity(true);
f.Property(b => b.Name).IsNullable(false); 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()) using (var uow = fsql.CreateUnitOfWork())
{ {
@ -140,7 +154,7 @@ namespace FreeSql.Tests {
//已关闭工作单元提不提交都没影响此处注释来确定工作单元开关是否生效关闭了不Commit也应该插入数据 //已关闭工作单元提不提交都没影响此处注释来确定工作单元开关是否生效关闭了不Commit也应该插入数据
//uow.Commit(); //uow.Commit();
} }
Assert.True(flowRepos.Select.Any(a => a.UserId == 1 && a.Name == "aaa")); Assert.True(flowRepos.Select.Any(a => a.UserId == 1 && a.Name == "aaa"));
} }
@ -149,7 +163,7 @@ namespace FreeSql.Tests {
[Fact] [Fact]
public void UnitOfWorkRepositoryWithDisableAfterInsert() public void UnitOfWorkRepositoryWithDisableAfterInsert()
{ {
foreach (var fsql in new[] {g.sqlite,}) foreach (var fsql in new[] { g.sqlite, })
{ {
fsql.CodeFirst.ConfigEntity<FlowModel>(f => fsql.CodeFirst.ConfigEntity<FlowModel>(f =>
{ {
@ -227,35 +241,37 @@ namespace FreeSql.Tests {
} }
public partial class FlowModel { public partial class FlowModel
public int UserId { get; set; } {
public int Id { get; set; } public int UserId { get; set; }
public int? ParentId { get; set; } public int Id { get; set; }
public string Name { get; set; } public int? ParentId { get; set; }
public DateTime CreateTime { get; set; } public string Name { get; set; }
public DateTime LastModifyTime { get; set; } public DateTime CreateTime { get; set; }
public string Desc { get; set; } public DateTime LastModifyTime { get; set; }
} public string Desc { get; set; }
}
[Fact] [Fact]
public void AsType() { public void AsType()
g.sqlite.Insert(new AddUpdateInfo()).ExecuteAffrows(); {
g.sqlite.Insert(new AddUpdateInfo()).ExecuteAffrows();
var repos = g.sqlite.GetGuidRepository<object>(); var repos = g.sqlite.GetGuidRepository<object>();
repos.AsType(typeof(AddUpdateInfo)); repos.AsType(typeof(AddUpdateInfo));
var item = new AddUpdateInfo(); var item = new AddUpdateInfo();
repos.Insert(item); repos.Insert(item);
repos.Update(item); repos.Update(item);
item.Clicks += 1; item.Clicks += 1;
repos.InsertOrUpdate(item); repos.InsertOrUpdate(item);
var item2 = repos.Find(item.Id) as AddUpdateInfo; var item2 = repos.Find(item.Id) as AddUpdateInfo;
Assert.Equal(item.Clicks, item2.Clicks); Assert.Equal(item.Clicks, item2.Clicks);
repos.DataFilter.Apply("xxx", a => (a as AddUpdateInfo).Clicks == 2); repos.DataFilter.Apply("xxx", a => (a as AddUpdateInfo).Clicks == 2);
Assert.Null(repos.Find(item.Id)); Assert.Null(repos.Find(item.Id));
} }
} }
} }

View File

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

View File

@ -4,83 +4,94 @@ using System.Diagnostics;
using System.Text; using System.Text;
public class g { public class g
{
static Lazy<IFreeSql> sqlserverLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder() 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") .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true) .UseAutoSyncStructure(true)
.UseMonitorCommand( .UseMonitorCommand(
cmd => { cmd =>
Trace.WriteLine(cmd.CommandText); {
}, //监听SQL命令对象在执行前 Trace.WriteLine(cmd.CommandText);
(cmd, traceLog) => { }, //监听SQL命令对象在执行前
Console.WriteLine(traceLog); (cmd, traceLog) =>
}) //监听SQL命令对象在执行后 {
.UseLazyLoading(true) Console.WriteLine(traceLog);
.UseNoneCommandParameter(true) }) //监听SQL命令对象在执行后
.Build()); .UseLazyLoading(true)
public static IFreeSql sqlserver => sqlserverLazy.Value; .UseNoneCommandParameter(true)
.Build());
public static IFreeSql sqlserver => sqlserverLazy.Value;
static Lazy<IFreeSql> mysqlLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder() 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") .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) .UseAutoSyncStructure(true)
.UseMonitorCommand( .UseMonitorCommand(
cmd => { cmd =>
Trace.WriteLine(cmd.CommandText); {
}, //监听SQL命令对象在执行前 Trace.WriteLine(cmd.CommandText);
(cmd, traceLog) => { }, //监听SQL命令对象在执行前
Console.WriteLine(traceLog); (cmd, traceLog) =>
}) //监听SQL命令对象在执行后 {
.UseLazyLoading(true) Console.WriteLine(traceLog);
.UseNoneCommandParameter(true) }) //监听SQL命令对象在执行后
.Build()); .UseLazyLoading(true)
public static IFreeSql mysql => mysqlLazy.Value; .UseNoneCommandParameter(true)
.Build());
public static IFreeSql mysql => mysqlLazy.Value;
static Lazy<IFreeSql> pgsqlLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder() 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") .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) .UseAutoSyncStructure(true)
.UseSyncStructureToLower(true) .UseSyncStructureToLower(true)
.UseLazyLoading(true) .UseLazyLoading(true)
.UseMonitorCommand( .UseMonitorCommand(
cmd => { cmd =>
Trace.WriteLine(cmd.CommandText); {
}, //监听SQL命令对象在执行前 Trace.WriteLine(cmd.CommandText);
(cmd, traceLog) => { }, //监听SQL命令对象在执行前
Console.WriteLine(traceLog); (cmd, traceLog) =>
}) //监听SQL命令对象在执行后 {
.UseNoneCommandParameter(true) Console.WriteLine(traceLog);
.Build()); }) //监听SQL命令对象在执行后
public static IFreeSql pgsql => pgsqlLazy.Value; .UseNoneCommandParameter(true)
.Build());
public static IFreeSql pgsql => pgsqlLazy.Value;
static Lazy<IFreeSql> oracleLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder() 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") .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) .UseAutoSyncStructure(true)
.UseLazyLoading(true) .UseLazyLoading(true)
.UseSyncStructureToUpper(true) .UseSyncStructureToUpper(true)
.UseNoneCommandParameter(true) .UseNoneCommandParameter(true)
.UseMonitorCommand( .UseMonitorCommand(
cmd => { cmd =>
Trace.WriteLine(cmd.CommandText); {
}, //监听SQL命令对象在执行前 Trace.WriteLine(cmd.CommandText);
(cmd, traceLog) => { }, //监听SQL命令对象在执行前
Console.WriteLine(traceLog); (cmd, traceLog) =>
}) //监听SQL命令对象在执行后 {
.Build()); Console.WriteLine(traceLog);
public static IFreeSql oracle => oracleLazy.Value; }) //监听SQL命令对象在执行后
.Build());
public static IFreeSql oracle => oracleLazy.Value;
static Lazy<IFreeSql> sqliteLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder() 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") .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|/document22.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true) .UseAutoSyncStructure(true)
.UseLazyLoading(true) .UseLazyLoading(true)
.UseMonitorCommand( .UseMonitorCommand(
cmd => { cmd =>
Trace.WriteLine(cmd.CommandText); {
}, //监听SQL命令对象在执行前 Trace.WriteLine(cmd.CommandText);
(cmd, traceLog) => { }, //监听SQL命令对象在执行前
Console.WriteLine(traceLog); (cmd, traceLog) =>
}) //监听SQL命令对象在执行后 {
.UseNoneCommandParameter(true) Console.WriteLine(traceLog);
.Build()); }) //监听SQL命令对象在执行后
public static IFreeSql sqlite => sqliteLazy.Value; .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.Tasks;
using System.Threading; using System.Threading;
namespace FreeSql.Tests.PerformanceTest { namespace FreeSql.Tests.PerformanceTest
public class MySqlAdoTest { {
public class MySqlAdoTest
{
[Fact] [Fact]
public void Query() { public void Query()
var sb = new StringBuilder(); {
var time = new Stopwatch(); var sb = new StringBuilder();
var time = new Stopwatch();
time.Restart(); time.Restart();
List<xxx> dplist1 = null; List<xxx> dplist1 = null;
using (var conn = g.mysql.Ado.MasterPool.Get()) { using (var conn = g.mysql.Ado.MasterPool.Get())
dplist1 = Dapper.SqlMapper.Query<xxx>(conn.Value, "select * from song").ToList(); {
} 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.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper");
time.Restart(); time.Restart();
List<(int, string, string)> dplist2 = null; List<(int, string, string)> dplist2 = null;
using (var conn = g.mysql.Ado.MasterPool.Get()) { using (var conn = g.mysql.Ado.MasterPool.Get())
dplist2 = Dapper.SqlMapper.Query<(int, string, string)>(conn.Value, "select * from song").ToList(); {
} 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.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {dplist2.Count}; ORM: Dapper");
time.Restart(); time.Restart();
List<dynamic> dplist3 = null; List<dynamic> dplist3 = null;
using (var conn = g.mysql.Ado.MasterPool.Get()) { using (var conn = g.mysql.Ado.MasterPool.Get())
dplist3 = Dapper.SqlMapper.Query<dynamic>(conn.Value, "select * from song").ToList(); {
} 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.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(); time.Restart();
var t3 = g.mysql.Ado.Query<xxx>("select * from song"); var t3 = g.mysql.Ado.Query<xxx>("select * from song");
time.Stop(); time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {t3.Count}; ORM: FreeSql*"); sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {t3.Count}; ORM: FreeSql*");
time.Restart(); time.Restart();
var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song"); var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song");
time.Stop(); time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {t4.Count}; ORM: FreeSql*"); sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {t4.Count}; ORM: FreeSql*");
time.Restart(); time.Restart();
var t41 = g.mysql.Select<xxx>().ToList<(int, string, string)>("id,title,url"); var t41 = g.mysql.Select<xxx>().ToList<(int, string, string)>("id,title,url");
time.Stop(); time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query ToList<Tuple> Counts: {t41.Count}; ORM: FreeSql*"); sb.AppendLine($"Elapsed: {time.Elapsed}; Query ToList<Tuple> Counts: {t41.Count}; ORM: FreeSql*");
time.Restart(); time.Restart();
var t5 = g.mysql.Ado.Query<dynamic>("select * from song"); var t5 = g.mysql.Ado.Query<dynamic>("select * from song");
time.Stop(); time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {t3.Count}; ORM: FreeSql*"); sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {t3.Count}; ORM: FreeSql*");
} }
[Fact] [Fact]
public void QueryLimit10() { public void QueryLimit10()
var sb = new StringBuilder(); {
var time = new Stopwatch(); var sb = new StringBuilder();
var time = new Stopwatch();
time.Restart(); time.Restart();
List<xxx> dplist1 = new List<xxx>(); List<xxx> dplist1 = new List<xxx>();
for (var a = 0; a < 10000; a++) { 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()); 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.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper");
time.Restart(); time.Restart();
List<(int, string, string)> dplist2 = new List<(int, string, string)>(); List<(int, string, string)> dplist2 = new List<(int, string, string)>();
for (var a = 0; a < 10000; a++) { 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()); 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.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {dplist2.Count}; ORM: Dapper");
time.Restart(); time.Restart();
List<dynamic> dplist3 = new List<dynamic>(); List<dynamic> dplist3 = new List<dynamic>();
for (var a = 0; a < 10000; a++) { 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()); 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.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {dplist3.Count}; ORM: Dapper");
time.Restart(); time.Restart();
List<xxx> t3 = new List<xxx>(); List<xxx> t3 = new List<xxx>();
for (var a = 0; a < 10000; a++) { for (var a = 0; a < 10000; a++)
t3.AddRange(g.mysql.Ado.Query<xxx>("select * from song limit 10")); {
} 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.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {t3.Count}; ORM: FreeSql*");
time.Restart(); time.Restart();
List<(int, string, string)> t4 = new List<(int, string, string)>(); List<(int, string, string)> t4 = new List<(int, string, string)>();
for (var a = 0; a < 10000; a++) { for (var a = 0; a < 10000; a++)
t4.AddRange(g.mysql.Ado.Query<(int, string, string)>("select * from song limit 10")); {
} 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.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {t4.Count}; ORM: FreeSql*");
time.Restart(); time.Restart();
List<dynamic> t5 = new List<dynamic>(); List<dynamic> t5 = new List<dynamic>();
for (var a = 0; a < 10000; a++) { for (var a = 0; a < 10000; a++)
t5.AddRange(g.mysql.Ado.Query<dynamic>("select * from song limit 10")); {
} 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.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {t3.Count}; ORM: FreeSql*");
} }
[Fact] [Fact]
public void ToList() { public void ToList()
var sb = new StringBuilder(); {
var time = new Stopwatch(); var sb = new StringBuilder();
var time = new Stopwatch();
//var t31 = g.mysql.Select<xxx>().ToList(); //var t31 = g.mysql.Select<xxx>().ToList();
time.Restart(); time.Restart();
var t3 = g.mysql.Select<xxx>().ToList(); var t3 = g.mysql.Select<xxx>().ToList();
time.Stop(); time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; ToList Entity Counts: {t3.Count}; ORM: FreeSql*"); sb.AppendLine($"Elapsed: {time.Elapsed}; ToList Entity Counts: {t3.Count}; ORM: FreeSql*");
time.Restart(); time.Restart();
List<xxx> dplist1 = null; List<xxx> dplist1 = null;
using (var conn = g.mysql.Ado.MasterPool.Get()) { using (var conn = g.mysql.Ado.MasterPool.Get())
dplist1 = Dapper.SqlMapper.Query<xxx>(conn.Value, "select * from song").ToList(); {
} 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.Stop();
} sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper");
}
[Fact] [Fact]
public void ToListLimit10() { public void ToListLimit10()
var sb = new StringBuilder(); {
var time = new Stopwatch(); var sb = new StringBuilder();
var time = new Stopwatch();
time.Restart(); time.Restart();
var t3Count = 0; var t3Count = 0;
var p3 = Parallel.For(1, 50, b => { var p3 = Parallel.For(1, 50, b =>
List<xxx> t3 = new List<xxx>(); {
for (var a = 0; a < 1000; a++) { List<xxx> t3 = new List<xxx>();
t3.AddRange(g.mysql.Select<xxx>().Limit(50).ToList()); for (var a = 0; a < 1000; a++)
} {
Interlocked.Add(ref t3Count, t3.Count); t3.AddRange(g.mysql.Select<xxx>().Limit(50).ToList());
}); }
while (p3.IsCompleted == false) ; Interlocked.Add(ref t3Count, t3.Count);
time.Stop(); });
sb.AppendLine($"Elapsed: {time.Elapsed}; ToList Entity Counts: {t3Count}; ORM: FreeSql*"); while (p3.IsCompleted == false) ;
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; ToList Entity Counts: {t3Count}; ORM: FreeSql*");
time.Restart(); time.Restart();
var dplist1Count = 0; var dplist1Count = 0;
var p1 = Parallel.For(1, 50, b => { var p1 = Parallel.For(1, 50, b =>
List<xxx> dplist1 = new List<xxx>(); {
for (var a = 0; a < 1000; a++) { List<xxx> dplist1 = new List<xxx>();
using (var conn = g.mysql.Ado.MasterPool.Get()) { for (var a = 0; a < 1000; a++)
dplist1.AddRange(Dapper.SqlMapper.Query<xxx>(conn.Value, "select * from song limit 50").ToList()); {
} using (var conn = g.mysql.Ado.MasterPool.Get())
} {
Interlocked.Add(ref dplist1Count, dplist1.Count); dplist1.AddRange(Dapper.SqlMapper.Query<xxx>(conn.Value, "select * from song limit 50").ToList());
}); }
while (p1.IsCompleted == false) ; }
time.Stop(); Interlocked.Add(ref dplist1Count, dplist1.Count);
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1Count}; ORM: Dapper"); });
} while (p1.IsCompleted == false) ;
time.Stop();
sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1Count}; ORM: Dapper");
}
[Table(Name = "song")] [Table(Name = "song")]
class xxx { class xxx
public int Id { get; set; } {
public string Title { get; set; } public int Id { get; set; }
//public string Url { get; set; } public string Title { get; set; }
public DateTime Create_time { get; set; } //public string Url { get; set; }
public bool Is_deleted { 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; using System.Text;
public class g { public class g
{
public static IFreeSql mysql = new FreeSql.FreeSqlBuilder() 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") .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) .UseAutoSyncStructure(false)
.Build(); .Build();
//public static IFreeSql sqlserver = new FreeSql.FreeSqlBuilder() //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") // .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=cms;Pooling=true;Max Pool Size=10")
// .UseAutoSyncStructure(false) // .UseAutoSyncStructure(false)
// .Build(); // .Build();
//public static IFreeSql pgsql = new FreeSql.FreeSqlBuilder() //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") // .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) // .UseAutoSyncStructure(false)
// .UseSyncStructureToLower(true) // .UseSyncStructureToLower(true)
// .Build(); // .Build();
//public static IFreeSql oracle = new FreeSql.FreeSqlBuilder() //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") // .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) // .UseAutoSyncStructure(false)
// .Build(); // .Build();
//public static IFreeSql sqlite = new FreeSql.FreeSqlBuilder() //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") // .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10")
// .UseAutoSyncStructure(false) // .UseAutoSyncStructure(false)
// .Build(); // .Build();
} }

View File

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

View File

@ -4,132 +4,143 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySqlConnector { namespace FreeSql.Tests.MySqlConnector
public class MySqlInsertTest { {
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")] [Table(Name = "tb_topic")]
class Topic { class Topic
[Column(IsIdentity = true, IsPrimary = true)] {
public int Id { get; set; } [Column(IsIdentity = true, IsPrimary = true)]
public int Clicks { get; set; } public int Id { get; set; }
public string Title { get; set; } public int Clicks { get; set; }
public DateTime CreateTime { get; set; } public string Title { get; set; }
} public DateTime CreateTime { get; set; }
class TestEnumInsertTb { }
[Column(IsIdentity = true)] class TestEnumInsertTb
public int id { get; set; } {
public TestEnumInserTbType type { get; set; } [Column(IsIdentity = true)]
public DateTime time { get; set; } = new DateTime(); public int id { get; set; }
} public TestEnumInserTbType type { get; set; }
enum TestEnumInserTbType { str1, biggit, sum211 } public DateTime time { get; set; } = new DateTime();
}
[Fact] enum TestEnumInserTbType { str1, biggit, sum211 }
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 });
var sql = insert.AppendData(items.First()).ToSql(); [Fact]
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); 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(); var sql = insert.AppendData(items.First()).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); 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(); sql = insert.AppendData(items).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); 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(); sql = insert.AppendData(items).InsertColumns(a => a.Title).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("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(); sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql();
Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES(@type_0, @time_0)", sql); 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(); sql = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211, time = DateTime.Now }).ToSql();
Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql); Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES(@type_0, @time_0)", sql);
}
[Fact] sql = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ToSql();
public void InsertColumns() { Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", 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 sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); [Fact]
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); 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(); var sql = insert.AppendData(items).InsertColumns(a => a.Title).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("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 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).IgnoreColumns(a => a.CreateTime).ToSql(); 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); 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(); var sql = insert.AppendData(items).IgnoreColumns(a => 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); 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 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, insert.AppendData(items.First()).ExecuteAffrows()); sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql();
Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); 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, insert.AppendData(items.First()).ExecuteAffrows());
Assert.Equal(1, g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteAffrows()); Assert.Equal(10, insert.AppendData(items).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.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.NotEqual(0, insert.AppendData(items.First()).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 });
//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] //insert.AppendData(items.First()).ExecuteInserted();
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 });
var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql(); [Fact]
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); 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(); 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), (@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); 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(); sql = insert.AppendData(items).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); 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(); sql = insert.AppendData(items).InsertColumns(a => a.Title).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); 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(); sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).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); 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(); sql = insert.AppendData(items).InsertColumns(a => a.Title).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); 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(); 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); 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(); sql = insert.AppendData(items).IgnoreColumns(a => 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); 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 System.Collections.Generic;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySqlConnector { namespace FreeSql.Tests.MySqlConnector
public class MySqlUpdateTest { {
IUpdate<Topic> update => g.mysql.Update<Topic>(); public class MySqlUpdateTest
{
IUpdate<Topic> update => g.mysql.Update<Topic>();
[Table(Name = "tb_topic")] [Table(Name = "tb_topic")]
class Topic { class Topic
[Column(IsIdentity = true, IsPrimary = true)] {
public int Id { get; set; } [Column(IsIdentity = true, IsPrimary = true)]
public int? Clicks { get; set; } public int Id { get; set; }
public string Title { get; set; } public int? Clicks { get; set; }
public DateTime CreateTime { get; set; } public string Title { get; set; }
} public DateTime CreateTime { get; set; }
class TestEnumUpdateTb { }
[Column(IsIdentity = true)] class TestEnumUpdateTb
public int id { get; set; } {
public TestEnumUpdateTbType type { get; set; } [Column(IsIdentity = true)]
public DateTime time { get; set; } = new DateTime(); public int id { get; set; }
} public TestEnumUpdateTbType type { get; set; }
enum TestEnumUpdateTbType { str1, biggit, sum211 } public DateTime time { get; set; } = new DateTime();
}
enum TestEnumUpdateTbType { str1, biggit, sum211 }
[Fact] [Fact]
public void Dywhere() { 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.Null(g.mysql.Update<Topic>().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='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 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 Topic { Id = 1, 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()); 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] [Fact]
public void SetSource() { 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 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>(); 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 }); 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", ""); 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); 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", ""); 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); 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", ""); 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); 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", ""); 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); 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(); var id = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0); Assert.True(id > 0);
Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type); 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", ""); 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); 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(); 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); 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", ""); 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); 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(); id = g.mysql.Insert<TestEnumUpdateTb>().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0); Assert.True(id > 0);
Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type); 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", ""); 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); 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(); 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); Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
} }
[Fact] [Fact]
public void IgnoreColumns() { 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); 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", ""); 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); 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", ""); 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); Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
} }
[Fact] [Fact]
public void UpdateColumns() { 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); 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", ""); 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); 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", ""); 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); Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
} }
[Fact] [Fact]
public void Set() { 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); 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", ""); 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); 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", ""); 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); 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", ""); 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); Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql);
int incrv = 10; int incrv = 10;
sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); 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); 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", ""); 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); 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", ""); 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); 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", ""); 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); 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(); var id = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0); Assert.True(id > 0);
sql = g.mysql.Update<TestEnumUpdateTb>().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ToSql().Replace("\r\n", ""); 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); 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(); 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); 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", ""); 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); 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(); 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); Assert.Equal(TestEnumUpdateTbType.str1, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
} }
[Fact] [Fact]
public void SetRaw() { 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); 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", ""); 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); Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
} }
[Fact] [Fact]
public void Where() { 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); 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", ""); 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); Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (id = @id)", sql);
var item = new Topic { Id = 1, Title = "newtitle" }; var item = new Topic { Id = 1, Title = "newtitle" };
sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql); Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql);
var items = new List<Topic>(); 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 }); 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", ""); 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); 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) 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", ""); .Set(a => a.type, TestEnumUpdateTbType.sum211).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0 AND `type` = 'str1')", sql); Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0 AND `type` = 'str1')", sql);
} }
[Fact] [Fact]
public void WhereExists() { public void WhereExists()
{
} }
[Fact] [Fact]
public void ExecuteAffrows() { public void ExecuteAffrows()
{
} }
[Fact] [Fact]
public void ExecuteUpdated() { public void ExecuteUpdated()
{
} }
[Fact] [Fact]
public void AsTable() { 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.Null(g.mysql.Update<Topic>().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='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 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 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)", g.mysql.Update<Topic>(new { id = 1 }).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 System.Numerics;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySqlConnectorMapType { namespace FreeSql.Tests.MySqlConnectorMapType
public class EnumTest { {
class EnumTestMap { public class EnumTest
public Guid id { get; set; } {
class EnumTestMap
{
public Guid id { get; set; }
[Column(MapType = typeof(string))] [Column(MapType = typeof(string))]
public ToStringMapEnum enum_to_string { get; set; } public ToStringMapEnum enum_to_string { get; set; }
[Column(MapType = typeof(string))] [Column(MapType = typeof(string))]
public ToStringMapEnum? enumnullable_to_string { get; set; } public ToStringMapEnum? enumnullable_to_string { get; set; }
[Column(MapType = typeof(int))] [Column(MapType = typeof(int))]
public ToStringMapEnum enum_to_int { get; set; } public ToStringMapEnum enum_to_int { get; set; }
[Column(MapType = typeof(int?))] [Column(MapType = typeof(int?))]
public ToStringMapEnum? enumnullable_to_int { get; set; } public ToStringMapEnum? enumnullable_to_int { get; set; }
} }
public enum ToStringMapEnum { , abc, } public enum ToStringMapEnum { , abc, }
[Fact] [Fact]
public void EnumToString() { public void EnumToString()
//insert {
var orm = g.mysql; //insert
var item = new EnumTestMap { }; var orm = g.mysql;
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); var item = new EnumTestMap { };
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
Assert.NotNull(find); var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.Equal(item.id, find.id); Assert.NotNull(find);
Assert.Equal(item.enum_to_string, find.enum_to_string); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_string); 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 }; item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string); Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); Assert.Equal(ToStringMapEnum.abc, find.enum_to_string);
//update all //update all
item.enum_to_string = ToStringMapEnum.; item.enum_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string); Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string); Assert.Equal(ToStringMapEnum., find.enum_to_string);
item.enum_to_string = ToStringMapEnum.; item.enum_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string); Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string); Assert.Equal(ToStringMapEnum., find.enum_to_string);
//update set //update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_string); 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()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); Assert.Equal(ToStringMapEnum.abc, find.enum_to_string);
//delete //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(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.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()); Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
} }
[Fact] [Fact]
public void EnumNullableToString() { public void EnumNullableToString()
//insert {
var orm = g.mysql; //insert
var item = new EnumTestMap { }; var orm = g.mysql;
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); var item = new EnumTestMap { };
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
Assert.NotNull(find); var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.Equal(item.id, find.id); Assert.NotNull(find);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_string); Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Null(find.enumnullable_to_string);
item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum. }; item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum. };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); Assert.Equal(ToStringMapEnum., find.enumnullable_to_string);
//update all //update all
item.enumnullable_to_string = ToStringMapEnum.; item.enumnullable_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); Assert.Equal(ToStringMapEnum., find.enumnullable_to_string);
item.enumnullable_to_string = null; item.enumnullable_to_string = null;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Null(find.enumnullable_to_string); Assert.Null(find.enumnullable_to_string);
//update set //update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); 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.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()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_string); Assert.Null(find.enumnullable_to_string);
//delete //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(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.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()); Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
} }
[Fact] [Fact]
public void EnumToInt() { public void EnumToInt()
//insert {
var orm = g.mysql; //insert
var item = new EnumTestMap { }; var orm = g.mysql;
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); var item = new EnumTestMap { };
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
Assert.NotNull(find); var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.Equal(item.id, find.id); Assert.NotNull(find);
Assert.Equal(item.enum_to_int, find.enum_to_int); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_int); 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 }; item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int); Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); Assert.Equal(ToStringMapEnum.abc, find.enum_to_int);
//update all //update all
item.enum_to_int = ToStringMapEnum.; item.enum_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int); Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int); Assert.Equal(ToStringMapEnum., find.enum_to_int);
item.enum_to_int = ToStringMapEnum.; item.enum_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int); Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int); Assert.Equal(ToStringMapEnum., find.enum_to_int);
//update set //update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_int); 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()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); Assert.Equal(ToStringMapEnum.abc, find.enum_to_int);
//delete //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(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.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()); Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
} }
[Fact] [Fact]
public void EnumNullableToInt() { public void EnumNullableToInt()
//insert {
var orm = g.mysql; //insert
var item = new EnumTestMap { }; var orm = g.mysql;
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); var item = new EnumTestMap { };
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
Assert.NotNull(find); var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.Equal(item.id, find.id); Assert.NotNull(find);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_int); Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Null(find.enumnullable_to_int);
item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum. }; item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum. };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); Assert.Equal(ToStringMapEnum., find.enumnullable_to_int);
//update all //update all
item.enumnullable_to_int = ToStringMapEnum.; item.enumnullable_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); Assert.Equal(ToStringMapEnum., find.enumnullable_to_int);
item.enumnullable_to_int = null; item.enumnullable_to_int = null;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Null(find.enumnullable_to_int); Assert.Null(find.enumnullable_to_int);
//update set //update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); 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.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()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_int); Assert.Null(find.enumnullable_to_int);
//delete //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(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.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()); 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 System.Text;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySqlConnector { namespace FreeSql.Tests.MySqlConnector
public class MySqlCodeFirstTest { {
public class MySqlCodeFirstTest
{
[Fact] [Fact]
public void _字段() { public void _字段()
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<2>(); {
g.mysql.CodeFirst.SyncStructure<2>(); var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<2>();
g.mysql.CodeFirst.SyncStructure<2>();
var item = new 2 { var item = new 2
= "测试标题", {
= DateTime.Now = "测试标题",
}; = DateTime.Now
Assert.Equal(1, g.mysql.Insert<2>().AppendData(item).ExecuteAffrows()); };
Assert.NotEqual(Guid.Empty, item.); Assert.Equal(1, g.mysql.Insert<2>().AppendData(item).ExecuteAffrows());
var item2 = g.mysql.Select<2>().Where(a => a. == item.).First(); Assert.NotEqual(Guid.Empty, item.);
Assert.NotNull(item2); var item2 = g.mysql.Select<2>().Where(a => a. == item.).First();
Assert.Equal(item., item2.); Assert.NotNull(item2);
Assert.Equal(item., item2.); Assert.Equal(item., item2.);
} Assert.Equal(item., item2.);
class 2 { }
[Column(IsPrimary = true)] class 2
public Guid { get; set; } {
[Column(IsPrimary = true)]
public Guid { get; set; }
public string { get; set; } public string { get; set; }
public DateTime { get; set; } public DateTime { get; set; }
} }
[Fact] [Fact]
public void AddUniques() { public void AddUniques()
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<AddUniquesInfo>(); {
g.mysql.CodeFirst.SyncStructure<AddUniquesInfo>(); var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<AddUniquesInfo>();
} g.mysql.CodeFirst.SyncStructure<AddUniquesInfo>();
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")] }
class AddUniquesInfo { [Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
public Guid id { get; set; } class AddUniquesInfo
[Column(Unique = "uk_phone")] {
public string phone { get; set; } public Guid id { get; set; }
[Column(Unique = "uk_phone")]
public string phone { get; set; }
[Column(Unique = "uk_group_index, uk_group_index22")] [Column(Unique = "uk_group_index, uk_group_index22")]
public string group { get; set; } public string group { get; set; }
[Column(Unique = "uk_group_index")] [Column(Unique = "uk_group_index")]
public int index { get; set; } public int index { get; set; }
[Column(Unique = "uk_group_index22")] [Column(Unique = "uk_group_index22")]
public string index22 { get; set; } public string index22 { get; set; }
} }
[Fact] [Fact]
public void AddField() { public void AddField()
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TopicAddField>(); {
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")] [Table(Name = "TopicAddField", OldName = "xxxtb.TopicAddField")]
public class TopicAddField { public class TopicAddField
[Column(IsIdentity = true)] {
public int? Id { get; set; } [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")] [Column(DbType = "varchar(200) not null", OldName = "title")]
public string title222 { get; set; } = "10"; public string title222 { get; set; } = "10";
[Column(IsIgnore = true)] [Column(IsIgnore = true)]
public DateTime ct { get; set; } = DateTime.Now; public DateTime ct { get; set; } = DateTime.Now;
} }
[Fact] [Fact]
public void GetComparisonDDLStatements() { public void GetComparisonDDLStatements()
{
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TableAllType>(); var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TableAllType>();
if (string.IsNullOrEmpty(sql) == false) { if (string.IsNullOrEmpty(sql) == false)
Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` ( {
Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` (
`Id` INT(11) NOT NULL AUTO_INCREMENT, `Id` INT(11) NOT NULL AUTO_INCREMENT,
`testFieldBool` BIT(1) NOT NULL, `testFieldBool` BIT(1) NOT NULL,
`testFieldSByte` TINYINT(3) NOT NULL, `testFieldSByte` TINYINT(3) NOT NULL,
@ -126,352 +137,363 @@ namespace FreeSql.Tests.MySqlConnector {
PRIMARY KEY (`Id`) PRIMARY KEY (`Id`)
) Engine=InnoDB; ) Engine=InnoDB;
", sql); ", sql);
} }
sql = g.mysql.CodeFirst.GetComparisonDDLStatements<Tb_alltype>(); sql = g.mysql.CodeFirst.GetComparisonDDLStatements<Tb_alltype>();
} }
IInsert<TableAllType> insert => g.mysql.Insert<TableAllType>(); IInsert<TableAllType> insert => g.mysql.Insert<TableAllType>();
ISelect<TableAllType> select => g.mysql.Select<TableAllType>(); ISelect<TableAllType> select => g.mysql.Select<TableAllType>();
[Fact] [Fact]
public void CurdAllField() { public void CurdAllField()
var item = new TableAllType { }; {
item.Id = (int)insert.AppendData(item).ExecuteIdentity(); var item = new TableAllType { };
item.Id = (int)insert.AppendData(item).ExecuteIdentity();
var newitem = select.Where(a => a.Id == item.Id).ToOne();
var newitem = select.Where(a => a.Id == item.Id).ToOne();
var item2 = new TableAllType {
testFieldBool = true, var item2 = new TableAllType
testFieldBoolNullable = true, {
testFieldByte = 255, testFieldBool = true,
testFieldByteNullable = 127, testFieldBoolNullable = true,
testFieldBytes = Encoding.UTF8.GetBytes("我是中国人"), testFieldByte = 255,
testFieldDateTime = DateTime.Now, testFieldByteNullable = 127,
testFieldDateTimeNullable = DateTime.Now.AddHours(-1), testFieldBytes = Encoding.UTF8.GetBytes("我是中国人"),
testFieldDecimal = 99.99M, testFieldDateTime = DateTime.Now,
testFieldDecimalNullable = 99.98M, testFieldDateTimeNullable = DateTime.Now.AddHours(-1),
testFieldDouble = 999.99, testFieldDecimal = 99.99M,
testFieldDoubleNullable = 999.98, testFieldDecimalNullable = 99.98M,
testFieldEnum1 = TableAllTypeEnumType1.e5, testFieldDouble = 999.99,
testFieldEnum1Nullable = TableAllTypeEnumType1.e3, testFieldDoubleNullable = 999.98,
testFieldEnum2 = TableAllTypeEnumType2.f2, testFieldEnum1 = TableAllTypeEnumType1.e5,
testFieldEnum2Nullable = TableAllTypeEnumType2.f3, testFieldEnum1Nullable = TableAllTypeEnumType1.e3,
testFieldFloat = 19.99F, testFieldEnum2 = TableAllTypeEnumType2.f2,
testFieldFloatNullable = 19.98F, testFieldEnum2Nullable = TableAllTypeEnumType2.f3,
testFieldGuid = Guid.NewGuid(), testFieldFloat = 19.99F,
testFieldGuidNullable = Guid.NewGuid(), testFieldFloatNullable = 19.98F,
testFieldInt = int.MaxValue, testFieldGuid = Guid.NewGuid(),
testFieldIntNullable = int.MinValue, testFieldGuidNullable = Guid.NewGuid(),
testFieldLineString = new MygisLineString(new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }), testFieldInt = int.MaxValue,
testFieldLong = long.MaxValue, testFieldIntNullable = int.MinValue,
testFieldMultiLineString = new MygisMultiLineString(new[] { testFieldLineString = new MygisLineString(new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }),
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }, testFieldLong = long.MaxValue,
new[] { new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 100) } }), testFieldMultiLineString = new MygisMultiLineString(new[] {
testFieldMultiPoint = new MygisMultiPoint(new[] { new MygisCoordinate2D(11, 11), new MygisCoordinate2D(51, 11) }), new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) },
testFieldMultiPolygon = new MygisMultiPolygon(new[] { new[] { new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 100) } }),
new MygisPolygon(new[] { testFieldMultiPoint = new MygisMultiPoint(new[] { new MygisCoordinate2D(11, 11), new MygisCoordinate2D(51, 11) }),
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, testFieldMultiPolygon = new MygisMultiPolygon(new[] {
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) },
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), new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
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) }, testFieldPoint = new MygisPoint(99, 99),
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, 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, new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
testFieldSByteNullable = 99, new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }),
testFieldShort = short.MaxValue, testFieldSByte = 100,
testFieldShortNullable = short.MinValue, testFieldSByteNullable = 99,
testFieldString = "我是中国人string", testFieldShort = short.MaxValue,
testFieldTimeSpan = TimeSpan.FromSeconds(999), testFieldShortNullable = short.MinValue,
testFieldTimeSpanNullable = TimeSpan.FromSeconds(60), testFieldString = "我是中国人string",
testFieldUInt = uint.MaxValue, testFieldTimeSpan = TimeSpan.FromSeconds(999),
testFieldUIntNullable = uint.MinValue, testFieldTimeSpanNullable = TimeSpan.FromSeconds(60),
testFieldULong = ulong.MaxValue, testFieldUInt = uint.MaxValue,
testFieldULongNullable = ulong.MinValue, testFieldUIntNullable = uint.MinValue,
testFieldUShort = ushort.MaxValue, testFieldULong = ulong.MaxValue,
testFieldUShortNullable = ushort.MinValue, testFieldULongNullable = ulong.MinValue,
testFielLongNullable = long.MinValue testFieldUShort = ushort.MaxValue,
}; testFieldUShortNullable = ushort.MinValue,
item2.Id = (int)insert.AppendData(item2).ExecuteIdentity(); testFielLongNullable = long.MinValue
var newitem2 = select.Where(a => a.Id == item2.Id).ToOne(); };
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")] [JsonObject(MemberSerialization.OptIn), Table(Name = "tb_alltype")]
public partial class Tb_alltype { public partial class Tb_alltype
{
[JsonProperty, Column(Name = "Id", DbType = "int(11)", IsPrimary = true, IsIdentity = true)] [JsonProperty, Column(Name = "Id", DbType = "int(11)", IsPrimary = true, IsIdentity = true)]
public int Id { get; set; } public int Id { get; set; }
[JsonProperty, Column(Name = "testFieldBool", DbType = "bit(1)")] [JsonProperty, Column(Name = "testFieldBool", DbType = "bit(1)")]
public bool TestFieldBool { get; set; } public bool TestFieldBool { get; set; }
[JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit(1)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit(1)", IsNullable = true)]
public bool? TestFieldBoolNullable { get; set; } public bool? TestFieldBoolNullable { get; set; }
[JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint(3) unsigned")] [JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint(3) unsigned")]
public byte TestFieldByte { get; set; } public byte TestFieldByte { get; set; }
[JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint(3) unsigned", IsNullable = true)] [JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint(3) unsigned", IsNullable = true)]
public byte? TestFieldByteNullable { get; set; } public byte? TestFieldByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldBytes", DbType = "varbinary(255)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldBytes", DbType = "varbinary(255)", IsNullable = true)]
public byte[] TestFieldBytes { get; set; } public byte[] TestFieldBytes { get; set; }
[JsonProperty, Column(Name = "testFieldDateTime", DbType = "datetime")] [JsonProperty, Column(Name = "testFieldDateTime", DbType = "datetime")]
public DateTime TestFieldDateTime { get; set; } public DateTime TestFieldDateTime { get; set; }
[JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)] [JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)]
public DateTime? TestFieldDateTimeNullable { get; set; } public DateTime? TestFieldDateTimeNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDecimal", DbType = "decimal(10,2)")] [JsonProperty, Column(Name = "testFieldDecimal", DbType = "decimal(10,2)")]
public decimal TestFieldDecimal { get; set; } public decimal TestFieldDecimal { get; set; }
[JsonProperty, Column(Name = "testFieldDecimalNullable", DbType = "decimal(10,2)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldDecimalNullable", DbType = "decimal(10,2)", IsNullable = true)]
public decimal? TestFieldDecimalNullable { get; set; } public decimal? TestFieldDecimalNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDouble", DbType = "double")] [JsonProperty, Column(Name = "testFieldDouble", DbType = "double")]
public double TestFieldDouble { get; set; } public double TestFieldDouble { get; set; }
[JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "double", IsNullable = true)] [JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "double", IsNullable = true)]
public double? TestFieldDoubleNullable { get; set; } public double? TestFieldDoubleNullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1", DbType = "enum('E1','E2','E3','E5')")] [JsonProperty, Column(Name = "testFieldEnum1", DbType = "enum('E1','E2','E3','E5')")]
public Tb_alltypeTESTFIELDENUM1 TestFieldEnum1 { get; set; } public Tb_alltypeTESTFIELDENUM1 TestFieldEnum1 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "enum('E1','E2','E3','E5')", IsNullable = true)] [JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "enum('E1','E2','E3','E5')", IsNullable = true)]
public Tb_alltypeTESTFIELDENUM1NULLABLE? TestFieldEnum1Nullable { get; set; } public Tb_alltypeTESTFIELDENUM1NULLABLE? TestFieldEnum1Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2", DbType = "set('F1','F2','F3')")] [JsonProperty, Column(Name = "testFieldEnum2", DbType = "set('F1','F2','F3')")]
public Tb_alltypeTESTFIELDENUM2 TestFieldEnum2 { get; set; } public Tb_alltypeTESTFIELDENUM2 TestFieldEnum2 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "set('F1','F2','F3')", IsNullable = true)] [JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "set('F1','F2','F3')", IsNullable = true)]
public Tb_alltypeTESTFIELDENUM2NULLABLE? TestFieldEnum2Nullable { get; set; } public Tb_alltypeTESTFIELDENUM2NULLABLE? TestFieldEnum2Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldFloat", DbType = "float")] [JsonProperty, Column(Name = "testFieldFloat", DbType = "float")]
public float TestFieldFloat { get; set; } public float TestFieldFloat { get; set; }
[JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "float", IsNullable = true)] [JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "float", IsNullable = true)]
public float? TestFieldFloatNullable { get; set; } public float? TestFieldFloatNullable { get; set; }
[JsonProperty, Column(Name = "testFieldGuid", DbType = "char(36)")] [JsonProperty, Column(Name = "testFieldGuid", DbType = "char(36)")]
public Guid TestFieldGuid { get; set; } public Guid TestFieldGuid { get; set; }
[JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "char(36)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "char(36)", IsNullable = true)]
public Guid? TestFieldGuidNullable { get; set; } public Guid? TestFieldGuidNullable { get; set; }
[JsonProperty, Column(Name = "testFieldInt", DbType = "int(11)")] [JsonProperty, Column(Name = "testFieldInt", DbType = "int(11)")]
public int TestFieldInt { get; set; } public int TestFieldInt { get; set; }
[JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int(11)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int(11)", IsNullable = true)]
public int? TestFieldIntNullable { get; set; } public int? TestFieldIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldLineString", DbType = "linestring", IsNullable = true)] [JsonProperty, Column(Name = "testFieldLineString", DbType = "linestring", IsNullable = true)]
public MygisGeometry TestFieldLineString { get; set; } public MygisGeometry TestFieldLineString { get; set; }
[JsonProperty, Column(Name = "testFieldLong", DbType = "bigint(20)")] [JsonProperty, Column(Name = "testFieldLong", DbType = "bigint(20)")]
public long TestFieldLong { get; set; } public long TestFieldLong { get; set; }
[JsonProperty, Column(Name = "testFieldMultiLineString", DbType = "multilinestring", IsNullable = true)] [JsonProperty, Column(Name = "testFieldMultiLineString", DbType = "multilinestring", IsNullable = true)]
public MygisGeometry TestFieldMultiLineString { get; set; } public MygisGeometry TestFieldMultiLineString { get; set; }
[JsonProperty, Column(Name = "testFieldMultiPoint", DbType = "multipoint", IsNullable = true)] [JsonProperty, Column(Name = "testFieldMultiPoint", DbType = "multipoint", IsNullable = true)]
public MygisGeometry TestFieldMultiPoint { get; set; } public MygisGeometry TestFieldMultiPoint { get; set; }
[JsonProperty, Column(Name = "testFieldMultiPolygon", DbType = "multipolygon", IsNullable = true)] [JsonProperty, Column(Name = "testFieldMultiPolygon", DbType = "multipolygon", IsNullable = true)]
public MygisGeometry TestFieldMultiPolygon { get; set; } public MygisGeometry TestFieldMultiPolygon { get; set; }
[JsonProperty, Column(Name = "testFieldPoint", DbType = "point", IsNullable = true)] [JsonProperty, Column(Name = "testFieldPoint", DbType = "point", IsNullable = true)]
public MygisGeometry TestFieldPoint { get; set; } public MygisGeometry TestFieldPoint { get; set; }
[JsonProperty, Column(Name = "testFieldPolygon", DbType = "polygon", IsNullable = true)] [JsonProperty, Column(Name = "testFieldPolygon", DbType = "polygon", IsNullable = true)]
public MygisGeometry TestFieldPolygon { get; set; } public MygisGeometry TestFieldPolygon { get; set; }
[JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint(3)")] [JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint(3)")]
public sbyte TestFieldSByte { get; set; } public sbyte TestFieldSByte { get; set; }
[JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint(3)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint(3)", IsNullable = true)]
public sbyte? TestFieldSByteNullable { get; set; } public sbyte? TestFieldSByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldShort", DbType = "smallint(6)")] [JsonProperty, Column(Name = "testFieldShort", DbType = "smallint(6)")]
public short TestFieldShort { get; set; } public short TestFieldShort { get; set; }
[JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint(6)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint(6)", IsNullable = true)]
public short? TestFieldShortNullable { get; set; } public short? TestFieldShortNullable { get; set; }
[JsonProperty, Column(Name = "testFieldString", DbType = "varchar(255)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldString", DbType = "varchar(255)", IsNullable = true)]
public string TestFieldString { get; set; } public string TestFieldString { get; set; }
[JsonProperty, Column(Name = "testFieldTimeSpan", DbType = "time")] [JsonProperty, Column(Name = "testFieldTimeSpan", DbType = "time")]
public TimeSpan TestFieldTimeSpan { get; set; } public TimeSpan TestFieldTimeSpan { get; set; }
[JsonProperty, Column(Name = "testFieldTimeSpanNullable", DbType = "time", IsNullable = true)] [JsonProperty, Column(Name = "testFieldTimeSpanNullable", DbType = "time", IsNullable = true)]
public TimeSpan? TestFieldTimeSpanNullable { get; set; } public TimeSpan? TestFieldTimeSpanNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUInt", DbType = "int(10) unsigned")] [JsonProperty, Column(Name = "testFieldUInt", DbType = "int(10) unsigned")]
public uint TestFieldUInt { get; set; } public uint TestFieldUInt { get; set; }
[JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int(10) unsigned", IsNullable = true)] [JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int(10) unsigned", IsNullable = true)]
public uint? TestFieldUIntNullable { get; set; } public uint? TestFieldUIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldULong", DbType = "bigint(20) unsigned")] [JsonProperty, Column(Name = "testFieldULong", DbType = "bigint(20) unsigned")]
public ulong TestFieldULong { get; set; } public ulong TestFieldULong { get; set; }
[JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint(20) unsigned", IsNullable = true)] [JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint(20) unsigned", IsNullable = true)]
public ulong? TestFieldULongNullable { get; set; } public ulong? TestFieldULongNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint(5) unsigned")] [JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint(5) unsigned")]
public ushort TestFieldUShort { get; set; } public ushort TestFieldUShort { get; set; }
[JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint(5) unsigned", IsNullable = true)] [JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint(5) unsigned", IsNullable = true)]
public ushort? TestFieldUShortNullable { get; set; } public ushort? TestFieldUShortNullable { get; set; }
[JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint(20)", IsNullable = true)] [JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint(20)", IsNullable = true)]
public long? TestFielLongNullable { get; set; } public long? TestFielLongNullable { get; set; }
internal static IFreeSql mysql => null; internal static IFreeSql mysql => null;
public static FreeSql.ISelect<Tb_alltype> Select => mysql.Select<Tb_alltype>(); public static FreeSql.ISelect<Tb_alltype> Select => mysql.Select<Tb_alltype>();
public static long Delete(int Id) { public static long Delete(int Id)
var affrows = mysql.Delete<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows(); {
return affrows; var affrows = mysql.Delete<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows();
} return affrows;
}
/// <summary> /// <summary>
/// 保存或添加,如果主键有值则尝试 Update如果影响的行为 0 则尝试 Insert /// 保存或添加,如果主键有值则尝试 Update如果影响的行为 0 则尝试 Insert
/// </summary> /// </summary>
public void Save() { public void Save()
if (this.Id != default(int)) { {
var affrows = mysql.Update<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows(); if (this.Id != default(int))
if (affrows > 0) return; {
} var affrows = mysql.Update<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows();
this.Id = (int)mysql.Insert<Tb_alltype>().AppendData(this).ExecuteIdentity(); if (affrows > 0) return;
} }
this.Id = (int)mysql.Insert<Tb_alltype>().AppendData(this).ExecuteIdentity();
}
} }
public enum Tb_alltypeTESTFIELDENUM1 { public enum Tb_alltypeTESTFIELDENUM1
E1 = 1, E2, E3, E5 {
} E1 = 1, E2, E3, E5
public enum Tb_alltypeTESTFIELDENUM1NULLABLE { }
E1 = 1, E2, E3, E5 public enum Tb_alltypeTESTFIELDENUM1NULLABLE
} {
[Flags] E1 = 1, E2, E3, E5
public enum Tb_alltypeTESTFIELDENUM2 : long { }
F1 = 1, F2 = 2, F3 = 4 [Flags]
} public enum Tb_alltypeTESTFIELDENUM2 : long
[Flags] {
public enum Tb_alltypeTESTFIELDENUM2NULLABLE : long { F1 = 1, F2 = 2, F3 = 4
F1 = 1, F2 = 2, F3 = 4 }
} [Flags]
public enum Tb_alltypeTESTFIELDENUM2NULLABLE : long
{
F1 = 1, F2 = 2, F3 = 4
}
[Table(Name = "tb_alltype")] [Table(Name = "tb_alltype")]
class TableAllType { class TableAllType
[Column(IsIdentity = true, IsPrimary = true)] {
public int Id { get; set; } [Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public bool testFieldBool { get; set; }
public sbyte testFieldSByte { get; set; } public bool testFieldBool { get; set; }
public short testFieldShort { get; set; } public sbyte testFieldSByte { get; set; }
public int testFieldInt { get; set; } public short testFieldShort { get; set; }
public long testFieldLong { get; set; } public int testFieldInt { get; set; }
public byte testFieldByte { get; set; } public long testFieldLong { get; set; }
public ushort testFieldUShort { get; set; } public byte testFieldByte { get; set; }
public uint testFieldUInt { get; set; } public ushort testFieldUShort { get; set; }
public ulong testFieldULong { get; set; } public uint testFieldUInt { get; set; }
public double testFieldDouble { get; set; } public ulong testFieldULong { get; set; }
public float testFieldFloat { get; set; } public double testFieldDouble { get; set; }
public decimal testFieldDecimal { get; set; } public float testFieldFloat { get; set; }
public TimeSpan testFieldTimeSpan { get; set; } public decimal testFieldDecimal { get; set; }
public DateTime testFieldDateTime { get; set; } public TimeSpan testFieldTimeSpan { get; set; }
public byte[] testFieldBytes { get; set; } public DateTime testFieldDateTime { get; set; }
public string testFieldString { get; set; } public byte[] testFieldBytes { get; set; }
public Guid testFieldGuid { get; set; } public string testFieldString { get; set; }
public Guid testFieldGuid { get; set; }
public bool? testFieldBoolNullable { get; set; }
public sbyte? testFieldSByteNullable { get; set; } public bool? testFieldBoolNullable { get; set; }
public short? testFieldShortNullable { get; set; } public sbyte? testFieldSByteNullable { get; set; }
public int? testFieldIntNullable { get; set; } public short? testFieldShortNullable { get; set; }
public long? testFielLongNullable { get; set; } public int? testFieldIntNullable { get; set; }
public byte? testFieldByteNullable { get; set; } public long? testFielLongNullable { get; set; }
public ushort? testFieldUShortNullable { get; set; } public byte? testFieldByteNullable { get; set; }
public uint? testFieldUIntNullable { get; set; } public ushort? testFieldUShortNullable { get; set; }
public ulong? testFieldULongNullable { get; set; } public uint? testFieldUIntNullable { get; set; }
public double? testFieldDoubleNullable { get; set; } public ulong? testFieldULongNullable { get; set; }
public float? testFieldFloatNullable { get; set; } public double? testFieldDoubleNullable { get; set; }
public decimal? testFieldDecimalNullable { get; set; } public float? testFieldFloatNullable { get; set; }
public TimeSpan? testFieldTimeSpanNullable { get; set; } public decimal? testFieldDecimalNullable { get; set; }
public DateTime? testFieldDateTimeNullable { get; set; } public TimeSpan? testFieldTimeSpanNullable { get; set; }
public Guid? testFieldGuidNullable { get; set; } public DateTime? testFieldDateTimeNullable { get; set; }
public Guid? testFieldGuidNullable { get; set; }
public MygisPoint testFieldPoint { get; set; }
public MygisLineString testFieldLineString { get; set; } public MygisPoint testFieldPoint { get; set; }
public MygisPolygon testFieldPolygon { get; set; } public MygisLineString testFieldLineString { get; set; }
public MygisMultiPoint testFieldMultiPoint { get; set; } public MygisPolygon testFieldPolygon { get; set; }
public MygisMultiLineString testFieldMultiLineString { get; set; } public MygisMultiPoint testFieldMultiPoint { get; set; }
public MygisMultiPolygon testFieldMultiPolygon { get; set; } public MygisMultiLineString testFieldMultiLineString { get; set; }
public MygisMultiPolygon testFieldMultiPolygon { get; set; }
public TableAllTypeEnumType1 testFieldEnum1 { get; set; }
public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } public TableAllTypeEnumType1 testFieldEnum1 { get; set; }
public TableAllTypeEnumType2 testFieldEnum2 { get; set; } public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; }
public TableAllTypeEnumType2? testFieldEnum2Nullable { 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 } 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 System;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySqlConnector { namespace FreeSql.Tests.MySqlConnector
public class MySqlAdoTest { {
[Fact] public class MySqlAdoTest
public void Pool() { {
var t1 = g.mysql.Ado.MasterPool.StatisticsFullily; [Fact]
} public void Pool()
{
var t1 = g.mysql.Ado.MasterPool.StatisticsFullily;
}
[Fact] [Fact]
public void SlavePools() { public void SlavePools()
var t2 = g.mysql.Ado.SlavePools.Count; {
} var t2 = g.mysql.Ado.SlavePools.Count;
}
[Fact] [Fact]
public void ExecuteReader() { public void ExecuteReader()
{
}
[Fact]
public void ExecuteArray() {
}
[Fact]
public void ExecuteNonQuery() {
}
[Fact]
public void ExecuteScalar() {
}
[Fact] }
public void Query() { [Fact]
var t3 = g.mysql.Ado.Query<xxx>("select * from song"); 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 { [Fact]
public int Id { get; set; } public void Query()
public string Path { get; set; } {
public string Title2 { get; set; } 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 System.Linq;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySqlConnectorExpression { namespace FreeSql.Tests.MySqlConnectorExpression
public class ConvertTest { {
public class ConvertTest
{
ISelect<Topic> select => g.mysql.Select<Topic>(); ISelect<Topic> select => g.mysql.Select<Topic>();
[Table(Name = "tb_topic")] [Table(Name = "tb_topic")]
class Topic { class Topic
[Column(IsIdentity = true, IsPrimary = true)] {
public int Id { get; set; } [Column(IsIdentity = true, IsPrimary = true)]
public int Clicks { get; set; } public int Id { get; set; }
public int TypeGuid { get; set; } public int Clicks { get; set; }
public TestTypeInfo Type { get; set; } public int TypeGuid { get; set; }
public string Title { get; set; } public TestTypeInfo Type { get; set; }
public DateTime CreateTime { get; set; } public string Title { get; set; }
} public DateTime CreateTime { get; set; }
class TestTypeInfo { }
public int Guid { get; set; } class TestTypeInfo
public int ParentId { get; set; } {
public TestTypeParentInfo Parent { get; set; } public int Guid { get; set; }
public string Name { get; set; } public int ParentId { get; set; }
} public TestTypeParentInfo Parent { get; set; }
class TestTypeParentInfo { public string Name { get; set; }
public int Id { 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] [Fact]
public void ToBoolean() { public void ToBoolean()
var data = new List<object>(); {
data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); var data = new List<object>();
data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); 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() { [Fact]
var data = new List<object>(); public void ToByte()
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()); var data = new List<object>();
} data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList());
[Fact] data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList());
public void ToChar() { }
var data = new List<object>(); [Fact]
data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); public void ToChar()
data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); {
} var data = new List<object>();
[Fact] data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList());
public void ToDateTime() { data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList());
var data = new List<object>(); }
data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); [Fact]
data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); public void ToDateTime()
} {
[Fact] var data = new List<object>();
public void ToDecimal() { data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList());
var data = new List<object>(); data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList());
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 ToDecimal()
[Fact] {
public void ToDouble() { var data = new List<object>();
var data = new List<object>(); data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList());
data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList());
data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); }
} [Fact]
[Fact] public void ToDouble()
public void ToInt16() { {
var data = new List<object>(); var data = new List<object>();
data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList());
data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList());
} }
[Fact] [Fact]
public void ToInt32() { public void ToInt16()
var data = new List<object>(); {
data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); var data = new List<object>();
data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList());
data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList());
} }
[Fact] [Fact]
public void ToInt64() { public void ToInt32()
var data = new List<object>(); {
data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); var data = new List<object>();
data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); data.Add(select.Where(a => (int)a.Clicks > 0).ToList());
} data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList());
[Fact] data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList());
public void ToSByte() { }
var data = new List<object>(); [Fact]
data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); public void ToInt64()
data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); {
} var data = new List<object>();
[Fact] data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList());
public void ToSingle() { data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList());
var data = new List<object>(); }
data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); [Fact]
data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); public void ToSByte()
} {
[Fact] var data = new List<object>();
public void this_ToString() { data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList());
var data = new List<object>(); data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList());
data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); }
data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); [Fact]
} public void ToSingle()
[Fact] {
public void ToUInt16() { var data = new List<object>();
var data = new List<object>(); data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList());
data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList());
data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); }
} [Fact]
[Fact] public void this_ToString()
public void ToUInt32() { {
var data = new List<object>(); var data = new List<object>();
data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList());
data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList());
} }
[Fact] [Fact]
public void ToUInt64() { public void ToUInt16()
var data = new List<object>(); {
data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); var data = new List<object>();
data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); 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] [Fact]
public void Guid_Parse() { public void Guid_Parse()
var data = new List<object>(); {
data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList()); var data = new List<object>();
} data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList());
}
[Fact] [Fact]
public void Guid_NewGuid() { public void Guid_NewGuid()
var data = new List<object>(); {
//data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); var data = new List<object>();
} //data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList());
}
[Fact] [Fact]
public void Random() { public void Random()
var data = new List<object>(); {
data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); var data = new List<object>();
data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); 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 System.Linq;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySqlConnectorExpression { namespace FreeSql.Tests.MySqlConnectorExpression
public class MathTest { {
public class MathTest
{
ISelect<Topic> select => g.mysql.Select<Topic>(); ISelect<Topic> select => g.mysql.Select<Topic>();
[Table(Name = "tb_topic")] [Table(Name = "tb_topic")]
class Topic { class Topic
[Column(IsIdentity = true, IsPrimary = true)] {
public int Id { get; set; } [Column(IsIdentity = true, IsPrimary = true)]
public int Clicks { get; set; } public int Id { get; set; }
public int TypeGuid { get; set; } public int Clicks { get; set; }
public TestTypeInfo Type { get; set; } public int TypeGuid { get; set; }
public string Title { get; set; } public TestTypeInfo Type { get; set; }
public DateTime CreateTime { get; set; } public string Title { get; set; }
} public DateTime CreateTime { get; set; }
class TestTypeInfo { }
public int Guid { get; set; } class TestTypeInfo
public int ParentId { get; set; } {
public TestTypeParentInfo Parent { get; set; } public int Guid { get; set; }
public string Name { get; set; } public int ParentId { get; set; }
} public TestTypeParentInfo Parent { get; set; }
class TestTypeParentInfo { public string Name { get; set; }
public int Id { 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] [Fact]
public void PI() { public void PI()
var data = new List<object>(); {
data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList()); var data = new List<object>();
} data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList());
[Fact] }
public void Abs() { [Fact]
var data = new List<object>(); public void Abs()
data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList()); {
} var data = new List<object>();
[Fact] data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList());
public void Sign() { }
var data = new List<object>(); [Fact]
data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList()); public void Sign()
} {
[Fact] var data = new List<object>();
public void Floor() { data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList());
var data = new List<object>(); }
data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList()); [Fact]
} public void Floor()
[Fact] {
public void Ceiling() { var data = new List<object>();
var data = new List<object>(); data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList());
data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList()); }
} [Fact]
[Fact] public void Ceiling()
public void Round() { {
var data = new List<object>(); 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.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList());
data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList()); }
} [Fact]
[Fact] public void Round()
public void Exp() { {
var data = new List<object>(); var data = new List<object>();
data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList()); 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 Log() { [Fact]
var data = new List<object>(); public void Exp()
data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList()); {
} var data = new List<object>();
[Fact] data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList());
public void Log10() { }
var data = new List<object>(); [Fact]
data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList()); public void Log()
} {
[Fact] var data = new List<object>();
public void Pow() { data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList());
var data = new List<object>(); }
data.Add(select.Where(a => Math.Pow(2, a.Clicks) == a.Clicks + 1).ToList()); [Fact]
} public void Log10()
[Fact] {
public void Sqrt() { var data = new List<object>();
var data = new List<object>(); data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList());
data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); }
} [Fact]
[Fact] public void Pow()
public void Cos() { {
var data = new List<object>(); var data = new List<object>();
data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); data.Add(select.Where(a => Math.Pow(2, a.Clicks) == a.Clicks + 1).ToList());
} }
[Fact] [Fact]
public void Sin() { public void Sqrt()
var data = new List<object>(); {
data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); var data = new List<object>();
} data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
[Fact] }
public void Tan() { [Fact]
var data = new List<object>(); public void Cos()
data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); {
} var data = new List<object>();
[Fact] data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
public void Acos() { }
var data = new List<object>(); [Fact]
data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); public void Sin()
} {
[Fact] var data = new List<object>();
public void Asin() { data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
var data = new List<object>(); }
data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); [Fact]
} public void Tan()
[Fact] {
public void Atan() { var data = new List<object>();
var data = new List<object>(); data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); }
} [Fact]
[Fact] public void Acos()
public void Atan2() { {
var data = new List<object>(); var data = new List<object>();
data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList()); data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList());
} }
[Fact] [Fact]
public void Truncate() { public void Asin()
var data = new List<object>(); {
data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList()); 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 System.Linq;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySqlConnectorExpression { namespace FreeSql.Tests.MySqlConnectorExpression
public class OtherTest { {
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(); [Fact]
var t22 = select.Where(a => a.testFieldBoolNullable != true).ToList(); public void Boolean()
var t33 = select.Where(a => a.testFieldBoolNullable == false).ToList(); {
var t44 = select.Where(a => !a.testFieldBoolNullable.Value).ToList(); var t1 = select.Where(a => a.testFieldBool == true).ToList();
var t55 = select.Where(a => a.testFieldBoolNullable.Value).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] var t11 = select.Where(a => a.testFieldBoolNullable == true).ToList();
public void Array() { var t22 = select.Where(a => a.testFieldBoolNullable != true).ToList();
int[] nullarr = null; var t33 = select.Where(a => a.testFieldBoolNullable == false).ToList();
Assert.Throws<MySqlException>(() => { select.Where(a => nullarr.Contains(a.testFieldInt)).ToList(); }); var t44 = select.Where(a => !a.testFieldBoolNullable.Value).ToList();
Assert.Throws<MySqlException>(() => { select.Where(a => new int[0].Contains(a.testFieldInt)).ToList(); }); var t55 = select.Where(a => a.testFieldBoolNullable.Value).ToList();
}
IEnumerable<int> testlinqlist = new List<int>(new[] { 1, 2, 3 }); [Fact]
var testlinq = select.Where(a => testlinqlist.Contains(a.testFieldInt)).ToList(); 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 IEnumerable<int> testlinqlist = new List<int>(new[] { 1, 2, 3 });
var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); var testlinq = select.Where(a => testlinqlist.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();
var inarray = new[] { 1, 2, 3 }; //in not in
var sql1111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList();
var sql1122 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList();
var sql1133 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList();
//in not in var inarray = new[] { 1, 2, 3 };
var sql11111 = select.Where(a => new List<int>() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); var sql1111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList();
var sql11222 = select.Where(a => new List<int>() { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); var sql1122 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList();
var sql11333 = select.Where(a => !new List<int>() { 1, 2, 3 }.Contains(a.testFieldInt)).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(); //in not in
var sql11222b = select.Where(a => new List<int>(new[] { 1, 2, 3 }).Contains(a.testFieldInt) == false).ToList(); var sql11111 = select.Where(a => new List<int>() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList();
var sql11333c = select.Where(a => !new List<int>(new[] { 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 sql11111a = select.Where(a => new List<int>(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList();
var sql111111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); var sql11222b = select.Where(a => new List<int>(new[] { 1, 2, 3 }).Contains(a.testFieldInt) == false).ToList();
var sql112222 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); var sql11333c = select.Where(a => !new List<int>(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList();
var sql113333 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList();
}
[Table(Name = "tb_alltype")] var inarray2 = new List<int>() { 1, 2, 3 };
class TableAllType { var sql111111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList();
[Column(IsIdentity = true, IsPrimary = true)] var sql112222 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList();
public int Id { get; set; } var sql113333 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList();
}
public bool testFieldBool { get; set; } [Table(Name = "tb_alltype")]
public sbyte testFieldSByte { get; set; } class TableAllType
public short testFieldShort { get; set; } {
public int testFieldInt { get; set; } [Column(IsIdentity = true, IsPrimary = true)]
public long testFieldLong { get; set; } public int Id { 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 bool testFieldBool { get; set; }
public sbyte? testFieldSByteNullable { get; set; } public sbyte testFieldSByte { get; set; }
public short? testFieldShortNullable { get; set; } public short testFieldShort { get; set; }
public int? testFieldIntNullable { get; set; } public int testFieldInt { get; set; }
public long? testFielLongNullable { get; set; } public long testFieldLong { get; set; }
public byte? testFieldByteNullable { get; set; } public byte testFieldByte { get; set; }
public ushort? testFieldUShortNullable { get; set; } public ushort testFieldUShort { get; set; }
public uint? testFieldUIntNullable { get; set; } public uint testFieldUInt { get; set; }
public ulong? testFieldULongNullable { get; set; } public ulong testFieldULong { get; set; }
public double? testFieldDoubleNullable { get; set; } public double testFieldDouble { get; set; }
public float? testFieldFloatNullable { get; set; } public float testFieldFloat { get; set; }
public decimal? testFieldDecimalNullable { get; set; } public decimal testFieldDecimal { get; set; }
public TimeSpan? testFieldTimeSpanNullable { get; set; } public TimeSpan testFieldTimeSpan { get; set; }
public DateTime? testFieldDateTimeNullable { get; set; } public DateTime testFieldDateTime { get; set; }
public Guid? testFieldGuidNullable { get; set; } public byte[] testFieldBytes { get; set; }
public string testFieldString { get; set; }
public Guid testFieldGuid { get; set; }
public MygisPoint testFieldPoint { get; set; } public bool? testFieldBoolNullable { get; set; }
public MygisLineString testFieldLineString { get; set; } public sbyte? testFieldSByteNullable { get; set; }
public MygisPolygon testFieldPolygon { get; set; } public short? testFieldShortNullable { get; set; }
public MygisMultiPoint testFieldMultiPoint { get; set; } public int? testFieldIntNullable { get; set; }
public MygisMultiLineString testFieldMultiLineString { get; set; } public long? testFielLongNullable { get; set; }
public MygisMultiPolygon testFieldMultiPolygon { 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 MygisPoint testFieldPoint { get; set; }
public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } public MygisLineString testFieldLineString { get; set; }
public TableAllTypeEnumType2 testFieldEnum2 { get; set; } public MygisPolygon testFieldPolygon { get; set; }
public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } public MygisMultiPoint testFieldMultiPoint { get; set; }
} public MygisMultiLineString testFieldMultiLineString { get; set; }
public MygisMultiPolygon testFieldMultiPolygon { get; set; }
public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } public TableAllTypeEnumType1 testFieldEnum1 { get; set; }
[Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } 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 System.Linq;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySqlConnectorExpression { namespace FreeSql.Tests.MySqlConnectorExpression
public class TimeSpanTest { {
public class TimeSpanTest
{
ISelect<Topic> select => g.mysql.Select<Topic>(); ISelect<Topic> select => g.mysql.Select<Topic>();
[Table(Name = "tb_topic")] [Table(Name = "tb_topic")]
class Topic { class Topic
[Column(IsIdentity = true, IsPrimary = true)] {
public int Id { get; set; } [Column(IsIdentity = true, IsPrimary = true)]
public int Clicks { get; set; } public int Id { get; set; }
public int TypeGuid { get; set; } public int Clicks { get; set; }
public TestTypeInfo Type { get; set; } public int TypeGuid { get; set; }
public string Title { get; set; } public TestTypeInfo Type { get; set; }
public DateTime CreateTime { get; set; } public string Title { get; set; }
} public DateTime CreateTime { get; set; }
class TestTypeInfo { }
public int Guid { get; set; } class TestTypeInfo
public int ParentId { get; set; } {
public TestTypeParentInfo Parent { get; set; } public int Guid { get; set; }
public string Name { get; set; } public int ParentId { get; set; }
} public TestTypeParentInfo Parent { get; set; }
class TestTypeParentInfo { public string Name { get; set; }
public int Id { 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] [Fact]
public void Zero() { public void Zero()
var data = new List<object>(); {
data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList()); var data = new List<object>();
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList());
//FROM `tb_topic` a //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > 0) //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() { [Fact]
var data = new List<object>(); public void MinValue()
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 var data = new List<object>();
//FROM `tb_topic` a data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList());
//WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580) //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
} //FROM `tb_topic` a
[Fact] //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580)
public void MaxValue() { }
var data = new List<object>(); [Fact]
data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList()); public void MaxValue()
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 {
//FROM `tb_topic` a var data = new List<object>();
//WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580) 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
[Fact] //FROM `tb_topic` a
public void Days() { //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580)
var data = new List<object>(); }
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList()); [Fact]
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 public void Days()
//FROM `tb_topic` a {
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0) var data = new List<object>();
} data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList());
[Fact] //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
public void Hours() { //FROM `tb_topic` a
var data = new List<object>(); //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0)
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 [Fact]
//FROM `tb_topic` a public void Hours()
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0) {
} var data = new List<object>();
[Fact] data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql());
public void Milliseconds() { //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
var data = new List<object>(); //FROM `tb_topic` a
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList()); //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0)
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 }
//FROM `tb_topic` a [Fact]
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0) public void Milliseconds()
} {
[Fact] var data = new List<object>();
public void Minutes() { data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList());
var data = new List<object>(); //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList()); //FROM `tb_topic` a
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0)
//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 Minutes()
[Fact] {
public void Seconds() { var data = new List<object>();
var data = new List<object>(); data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList());
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
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 //FROM `tb_topic` a
//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)
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0) }
} [Fact]
[Fact] public void Seconds()
public void Ticks() { {
var data = new List<object>(); var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList()); 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 //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a //FROM `tb_topic` a
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) * 10) > 0) //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0)
} }
[Fact] [Fact]
public void TotalDays() { public void Ticks()
var data = new List<object>(); {
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList()); var data = new List<object>();
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList());
//FROM `tb_topic` a //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0) //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 TotalHours() { [Fact]
var data = new List<object>(); public void TotalDays()
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 var data = new List<object>();
//FROM `tb_topic` a data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList());
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0) //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
} //FROM `tb_topic` a
[Fact] //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0)
public void TotalMilliseconds() { }
var data = new List<object>(); [Fact]
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList()); public void TotalHours()
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 {
//FROM `tb_topic` a var data = new List<object>();
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0) 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
[Fact] //FROM `tb_topic` a
public void TotalMinutes() { //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0)
var data = new List<object>(); }
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql()); [Fact]
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 public void TotalMilliseconds()
//FROM `tb_topic` a {
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0) var data = new List<object>();
} data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList());
[Fact] //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
public void TotalSeconds() { //FROM `tb_topic` a
var data = new List<object>(); //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0)
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 [Fact]
//FROM `tb_topic` a public void TotalMinutes()
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0) {
} var data = new List<object>();
[Fact] data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql());
public void Add() { //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
var data = new List<object>(); //FROM `tb_topic` a
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0)
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 }
//FROM `tb_topic` a [Fact]
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0) public void TotalSeconds()
} {
[Fact] var data = new List<object>();
public void Subtract() { data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList());
var data = new List<object>(); //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); //FROM `tb_topic` a
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0)
//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 Add()
[Fact] {
public void CompareTo() { var data = new List<object>();
var data = new List<object>(); data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList());
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
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 //FROM `tb_topic` a
//FROM `tb_topic` a //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0)
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) }
} [Fact]
[Fact] public void Subtract()
public void this_Equals() { {
var data = new List<object>(); var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList()); 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 //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a //FROM `tb_topic` a
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) - (1 * 86400000000)) > 0)
} }
[Fact] [Fact]
public void this_ToString() { public void CompareTo()
var data = new List<object>(); {
data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList()); var data = new List<object>();
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList());
//FROM `tb_topic` a //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//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') //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] [Fact]
public void TimeSpan_Compare() { public void TimeSpan_Compare()
var data = new List<object>(); {
data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList()); var data = new List<object>();
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList());
//FROM `tb_topic` a //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) //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() { [Fact]
var data = new List<object>(); public void TimeSpan_Equals()
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 var data = new List<object>();
//FROM `tb_topic` a data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList());
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
} //FROM `tb_topic` a
[Fact] //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000)))
public void TimeSpan_FromDays() { }
var data = new List<object>(); [Fact]
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); public void TimeSpan_FromDays()
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 {
//FROM `tb_topic` a var data = new List<object>();
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) 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
[Fact] //FROM `tb_topic` a
public void TimeSpan_FromHours() { //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000)))
var data = new List<object>(); }
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList()); [Fact]
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 public void TimeSpan_FromHours()
//FROM `tb_topic` a {
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000))) var data = new List<object>();
} data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList());
[Fact] //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
public void TimeSpan_FromMilliseconds() { //FROM `tb_topic` a
var data = new List<object>(); //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000)))
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 [Fact]
//FROM `tb_topic` a public void TimeSpan_FromMilliseconds()
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000))) {
} var data = new List<object>();
[Fact] data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList());
public void TimeSpan_FromMinutes() { //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
var data = new List<object>(); //FROM `tb_topic` a
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList()); //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000)))
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 }
//FROM `tb_topic` a [Fact]
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000))) public void TimeSpan_FromMinutes()
} {
[Fact] var data = new List<object>();
public void TimeSpan_FromSeconds() { data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList());
var data = new List<object>(); //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList()); //FROM `tb_topic` a
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000)))
//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_FromSeconds()
[Fact] {
public void TimeSpan_FromTicks() { var data = new List<object>();
var data = new List<object>(); data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList());
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
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 //FROM `tb_topic` a
//FROM `tb_topic` a //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000000)))
//WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 / 10))) }
} [Fact]
[Fact] public void TimeSpan_FromTicks()
public void TimeSpan_Parse() { {
var data = new List<object>(); var data = new List<object>();
data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList()); 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 //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a //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) //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 System;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySqlConnector { namespace FreeSql.Tests.MySqlConnector
public class MySqlDbFirstTest { {
[Fact] public class MySqlDbFirstTest
public void GetDatabases() { {
[Fact]
public void GetDatabases()
{
var t1 = g.mysql.DbFirst.GetDatabases(); var t1 = g.mysql.DbFirst.GetDatabases();
} }
[Fact] [Fact]
public void GetTablesByDatabase() { 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; using System.Text;
public class g { public class g
{
static Lazy<IFreeSql> mysqlLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder() 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") .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) .UseAutoSyncStructure(true)
.UseMonitorCommand( .UseMonitorCommand(
cmd => { cmd =>
Trace.WriteLine(cmd.CommandText); {
}, //监听SQL命令对象在执行前 Trace.WriteLine(cmd.CommandText);
(cmd, traceLog) => { }, //监听SQL命令对象在执行前
Console.WriteLine(traceLog); (cmd, traceLog) =>
}) //监听SQL命令对象在执行后 {
.UseLazyLoading(true) Console.WriteLine(traceLog);
.Build()); }) //监听SQL命令对象在执行后
public static IFreeSql mysql => mysqlLazy.Value; .UseLazyLoading(true)
.Build());
public static IFreeSql mysql => mysqlLazy.Value;
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,65 +1,70 @@
using Xunit; using Xunit;
namespace FreeSql.Tests.Extensions { namespace FreeSql.Tests.Extensions
public class StringExtensionsTest { {
[Fact] public class StringExtensionsTest
public void FormatMySql() { {
[Fact]
public void FormatMySql()
{
Assert.Empty(((string)null).FormatMySql("11")); 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 =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 ='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 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 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 not IS NULL", "a={0} and b={1} and c not in {2}".FormatMySql(1, null, null));
} }
[Fact] [Fact]
public void FormatSqlServer() { public void FormatSqlServer()
{
Assert.Empty(((string)null).FormatSqlServer("11")); 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 =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 ='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 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 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 not IS NULL", "a={0} and b={1} and c not in {2}".FormatSqlServer(1, null, null));
} }
[Fact] [Fact]
public void FormatPostgreSQL() { public void FormatPostgreSQL()
{
Assert.Empty(((string)null).FormatPostgreSQL("11")); 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 =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 ='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 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 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 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 System.Linq;
using Xunit; using Xunit;
namespace FreeSql.Tests.LinqToSql { namespace FreeSql.Tests.LinqToSql
{
class TestLinqToSql { class TestLinqToSql
public Guid id { get; set; } {
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; public DateTime createtime { get; set; } = DateTime.Now;
} }
class TestLinqToSqlComment { class TestLinqToSqlComment
public Guid id { get; set; } {
public Guid id { get; set; }
public Guid TestLinqToSqlId { get; set; } public Guid TestLinqToSqlId { get; set; }
public TestLinqToSql TEstLinqToSql { get; set; } public TestLinqToSql TEstLinqToSql { get; set; }
public string text { get; set; } public string text { get; set; }
public DateTime createtime { get; set; } = DateTime.Now;
}
public class SqliteLinqToSqlTests { public DateTime createtime { get; set; } = DateTime.Now;
}
[Fact] public class SqliteLinqToSqlTests
public void Where() { {
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
var t1 = (from a in g.sqlite.Select<TestLinqToSql>() [Fact]
where a.id == item.id public void Where()
select a).ToList(); {
Assert.True(t1.Any()); var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
Assert.Equal(item.id, t1[0].id); g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
}
[Fact] var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
public void Select() { where a.id == item.id
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; select a).ToList();
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows(); Assert.True(t1.Any());
Assert.Equal(item.id, t1[0].id);
}
var t1 = (from a in g.sqlite.Select<TestLinqToSql>() [Fact]
where a.id == item.id public void Select()
select new { a.id }).ToList(); {
Assert.True(t1.Any()); var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
Assert.Equal(item.id, t1[0].id); g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
}
[Fact] var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
public void GroupBy() { where a.id == item.id
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; select new { a.id }).ToList();
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows(); Assert.True(t1.Any());
Assert.Equal(item.id, t1[0].id);
}
var t1 = (from a in g.sqlite.Select<TestLinqToSql>() [Fact]
where a.id == item.id public void GroupBy()
group a by new {a.id, a.name } into g {
select new { var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
g.Key.id, g.Key.name, g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
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] var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
public void CaseWhen() { where a.id == item.id
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; group a by new { a.id, a.name } into g
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows(); 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>() [Fact]
where a.id == item.id public void CaseWhen()
select new { {
a.id, var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
a.name, g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
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] var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
public void Join() { where a.id == item.id
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; select new
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows(); {
var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() }; a.id,
g.sqlite.Insert<TestLinqToSqlComment>().AppendData(comment).ExecuteAffrows(); 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>() [Fact]
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId public void Join()
select a).ToList(); {
Assert.True(t1.Any()); var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
//Assert.Equal(item.id, t1[0].id); 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>() var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId
select new { a.id, bid = b.id }).ToList(); select a).ToList();
Assert.True(t2.Any()); Assert.True(t1.Any());
//Assert.Equal(item.id, t2[0].id); //Assert.Equal(item.id, t1[0].id);
//Assert.Equal(comment.id, t2[0].bid);
var t3 = (from a in g.sqlite.Select<TestLinqToSql>() var t2 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId 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();
select new { a.id, bid = b.id }).ToList(); Assert.True(t2.Any());
Assert.True(t3.Any()); //Assert.Equal(item.id, t2[0].id);
Assert.Equal(item.id, t3[0].id); //Assert.Equal(comment.id, t2[0].bid);
Assert.Equal(comment.id, t3[0].bid);
}
[Fact] var t3 = (from a in g.sqlite.Select<TestLinqToSql>()
public void LeftJoin() { join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; where a.id == item.id
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows(); select new { a.id, bid = b.id }).ToList();
var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() }; Assert.True(t3.Any());
g.sqlite.Insert<TestLinqToSqlComment>().AppendData(comment).ExecuteAffrows(); Assert.Equal(item.id, t3[0].id);
Assert.Equal(comment.id, t3[0].bid);
}
var t1 = (from a in g.sqlite.Select<TestLinqToSql>() [Fact]
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId into temp public void LeftJoin()
from tc in temp.DefaultIfEmpty() {
select a).ToList(); var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
Assert.True(t1.Any()); g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
//Assert.Equal(item.id, t1[0].id); 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>() var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId into temp join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId into temp
from tc in temp.DefaultIfEmpty() from tc in temp.DefaultIfEmpty()
select new { a.id, bid = tc.id }).ToList(); select a).ToList();
Assert.True(t2.Any()); Assert.True(t1.Any());
//Assert.Equal(item.id, t2[0].id); //Assert.Equal(item.id, t1[0].id);
//Assert.Equal(comment.id, t2[0].bid);
var t3 = (from a in g.sqlite.Select<TestLinqToSql>() var t2 = (from a in g.sqlite.Select<TestLinqToSql>()
join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId into temp join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId into temp
from tc in temp.DefaultIfEmpty() from tc in temp.DefaultIfEmpty()
where a.id == item.id select new { a.id, bid = tc.id }).ToList();
select new { a.id, bid = tc.id }).ToList(); Assert.True(t2.Any());
Assert.True(t3.Any()); //Assert.Equal(item.id, t2[0].id);
Assert.Equal(item.id, t3[0].id); //Assert.Equal(comment.id, t2[0].bid);
Assert.Equal(comment.id, t3[0].bid);
}
[Fact] var t3 = (from a in g.sqlite.Select<TestLinqToSql>()
public void From() { join b in g.sqlite.Select<TestLinqToSqlComment>() on a.id equals b.TestLinqToSqlId into temp
var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; from tc in temp.DefaultIfEmpty()
g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows(); where a.id == item.id
var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() }; select new { a.id, bid = tc.id }).ToList();
g.sqlite.Insert<TestLinqToSqlComment>().AppendData(comment).ExecuteAffrows(); 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>() [Fact]
from b in g.sqlite.Select<TestLinqToSqlComment>() public void From()
where a.id == b.TestLinqToSqlId {
select a).ToList(); var item = new TestLinqToSql { name = Guid.NewGuid().ToString() };
Assert.True(t1.Any()); g.sqlite.Insert<TestLinqToSql>().AppendData(item).ExecuteAffrows();
//Assert.Equal(item.id, t1[0].id); 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>() var t1 = (from a in g.sqlite.Select<TestLinqToSql>()
from b in g.sqlite.Select<TestLinqToSqlComment>() from b in g.sqlite.Select<TestLinqToSqlComment>()
where a.id == b.TestLinqToSqlId where a.id == b.TestLinqToSqlId
select new { a.id, bid = b.id }).ToList(); select a).ToList();
Assert.True(t2.Any()); Assert.True(t1.Any());
//Assert.Equal(item.id, t2[0].id); //Assert.Equal(item.id, t1[0].id);
//Assert.Equal(comment.id, t2[0].bid);
var t3 = (from a in g.sqlite.Select<TestLinqToSql>() var t2 = (from a in g.sqlite.Select<TestLinqToSql>()
from b in g.sqlite.Select<TestLinqToSqlComment>() from b in g.sqlite.Select<TestLinqToSqlComment>()
where a.id == b.TestLinqToSqlId where a.id == b.TestLinqToSqlId
where a.id == item.id select new { a.id, bid = b.id }).ToList();
select new { a.id, bid = b.id }).ToList(); Assert.True(t2.Any());
Assert.True(t3.Any()); //Assert.Equal(item.id, t2[0].id);
Assert.Equal(item.id, t3[0].id); //Assert.Equal(comment.id, t2[0].bid);
Assert.Equal(comment.id, t3[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 System.Linq;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySql { namespace FreeSql.Tests.MySql
public class MySqlDeleteTest { {
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")] [Table(Name = "tb_topic")]
class Topic { class Topic
[Column(IsIdentity = true, IsPrimary = true)] {
public int Id { get; set; } [Column(IsIdentity = true, IsPrimary = true)]
public int Clicks { get; set; } public int Id { get; set; }
public TestTypeInfo Type { get; set; } public int Clicks { get; set; }
public string Title { get; set; } public TestTypeInfo Type { get; set; }
public DateTime CreateTime { get; set; } public string Title { get; set; }
} public DateTime CreateTime { get; set; }
}
[Fact] [Fact]
public void Dywhere() { public void Dywhere()
Assert.Null(g.mysql.Delete<Topic>().ToSql()); {
var sql = g.mysql.Delete<Topic>(new[] { 1, 2 }).ToSql(); Assert.Null(g.mysql.Delete<Topic>().ToSql());
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql); 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(); sql = g.mysql.Delete<Topic>(new Topic { Id = 1, Title = "test" }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); 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(); 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); Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new { id = 1 }).ToSql(); sql = g.mysql.Delete<Topic>(new { id = 1 }).ToSql();
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
} }
[Fact] [Fact]
public void Where() { 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); 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", ""); sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (id = @id)", sql); Assert.Equal("DELETE FROM `tb_topic` WHERE (id = @id)", sql);
var item = new Topic { Id = 1, Title = "newtitle" }; var item = new Topic { Id = 1, Title = "newtitle" };
sql = delete.Where(item).ToSql().Replace("\r\n", ""); sql = delete.Where(item).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql);
var items = new List<Topic>(); 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 }); 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", ""); 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); Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql);
} }
[Fact] [Fact]
public void WhereExists() { public void WhereExists()
{
} }
[Fact] [Fact]
public void ExecuteAffrows() { public void ExecuteAffrows()
{
var id = g.mysql.Insert<Topic>(new Topic { Title = "xxxx" }).ExecuteIdentity(); var id = g.mysql.Insert<Topic>(new Topic { Title = "xxxx" }).ExecuteIdentity();
Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows()); Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows());
} }
[Fact] [Fact]
public void ExecuteDeleted() { public void ExecuteDeleted()
{
//delete.Where(a => a.Id > 0).ExecuteDeleted(); //delete.Where(a => a.Id > 0).ExecuteDeleted();
} }
[Fact] [Fact]
public void AsTable() { public void AsTable()
Assert.Null(g.mysql.Delete<Topic>().ToSql()); {
var sql = g.mysql.Delete<Topic>(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql(); Assert.Null(g.mysql.Delete<Topic>().ToSql());
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql); 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(); sql = g.mysql.Delete<Topic>(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql); 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(); 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); Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql);
sql = g.mysql.Delete<Topic>(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql(); sql = g.mysql.Delete<Topic>(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql();
Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql); Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql);
} }
} }
} }

View File

@ -4,133 +4,144 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySql { namespace FreeSql.Tests.MySql
public class MySqlInsertTest { {
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")] [Table(Name = "tb_topic")]
class Topic { class Topic
[Column(IsIdentity = true, IsPrimary = true)] {
public int Id { get; set; } [Column(IsIdentity = true, IsPrimary = true)]
public int Clicks { get; set; } public int Id { get; set; }
public TestTypeInfo Type { get; set; } public int Clicks { get; set; }
public string Title { get; set; } public TestTypeInfo Type { get; set; }
public DateTime CreateTime { get; set; } public string Title { get; set; }
} public DateTime CreateTime { get; set; }
class TestEnumInsertTb { }
[Column(IsIdentity = true)] class TestEnumInsertTb
public int id { get; set; } {
public TestEnumInserTbType type { get; set; } [Column(IsIdentity = true)]
public DateTime time { get; set; } = new DateTime(); public int id { get; set; }
} public TestEnumInserTbType type { get; set; }
enum TestEnumInserTbType { str1, biggit, sum211 } public DateTime time { get; set; } = new DateTime();
}
[Fact] enum TestEnumInserTbType { str1, biggit, sum211 }
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 });
var sql = insert.AppendData(items.First()).ToSql(); [Fact]
Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0)", sql); 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(); var sql = insert.AppendData(items.First()).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); 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(); sql = insert.AppendData(items).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); 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(); sql = insert.AppendData(items).InsertColumns(a => a.Title).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("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(); sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql();
Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES(?type_0, ?time_0)", sql); 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(); sql = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211, time = DateTime.Now }).ToSql();
Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql); Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES(?type_0, ?time_0)", sql);
}
[Fact] sql = g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ToSql();
public void InsertColumns() { Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", 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 sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); [Fact]
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); 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(); var sql = insert.AppendData(items).InsertColumns(a => a.Title).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("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 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).IgnoreColumns(a => a.CreateTime).ToSql(); 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); 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(); var sql = insert.AppendData(items).IgnoreColumns(a => 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); 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 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, insert.AppendData(items.First()).ExecuteAffrows()); sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql();
Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); 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, insert.AppendData(items.First()).ExecuteAffrows());
Assert.Equal(1, g.mysql.Insert<TestEnumInsertTb>().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteAffrows()); Assert.Equal(10, insert.AppendData(items).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.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.NotEqual(0, insert.AppendData(items.First()).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 });
//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] //insert.AppendData(items.First()).ExecuteInserted();
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 });
var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql(); [Fact]
Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0)", sql); 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(); 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), (?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); 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(); sql = insert.AppendData(items).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); 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(); sql = insert.AppendData(items).InsertColumns(a => a.Title).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); 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(); sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).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); 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(); sql = insert.AppendData(items).InsertColumns(a => a.Title).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); 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(); 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); 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(); sql = insert.AppendData(items).IgnoreColumns(a => 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); 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 System.Collections.Generic;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySql { namespace FreeSql.Tests.MySql
public class MySqlUpdateTest { {
IUpdate<Topic> update => g.mysql.Update<Topic>(); public class MySqlUpdateTest
{
IUpdate<Topic> update => g.mysql.Update<Topic>();
[Table(Name = "tb_topic")] [Table(Name = "tb_topic")]
class Topic { class Topic
[Column(IsIdentity = true, IsPrimary = true)] {
public int Id { get; set; } [Column(IsIdentity = true, IsPrimary = true)]
public int? Clicks { get; set; } public int Id { get; set; }
public TestTypeInfo Type { get; set; } public int? Clicks { get; set; }
public string Title { get; set; } public TestTypeInfo Type { get; set; }
public DateTime CreateTime { get; set; } public string Title { get; set; }
} public DateTime CreateTime { get; set; }
class TestEnumUpdateTb { }
[Column(IsIdentity = true)] class TestEnumUpdateTb
public int id { get; set; } {
public TestEnumUpdateTbType type { get; set; } [Column(IsIdentity = true)]
public DateTime time { get; set; } = new DateTime(); public int id { get; set; }
} public TestEnumUpdateTbType type { get; set; }
enum TestEnumUpdateTbType { str1, biggit, sum211 } public DateTime time { get; set; } = new DateTime();
}
enum TestEnumUpdateTbType { str1, biggit, sum211 }
[Fact] [Fact]
public void Dywhere() { 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.Null(g.mysql.Update<Topic>().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='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 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 Topic { Id = 1, 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()); 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] [Fact]
public void SetSource() { 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 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>(); 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 }); 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", ""); 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); 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", ""); 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); 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", ""); 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); 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", ""); 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); 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(); var id = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0); Assert.True(id > 0);
Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type); 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", ""); 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); 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(); 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); 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", ""); 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); 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(); id = g.mysql.Insert<TestEnumUpdateTb>().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0); Assert.True(id > 0);
Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type); 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", ""); 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); 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(); 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); Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
} }
[Fact] [Fact]
public void IgnoreColumns() { 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); 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", ""); 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); 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", ""); 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); Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
} }
[Fact] [Fact]
public void UpdateColumns() { 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); 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", ""); 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); 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", ""); 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); Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
} }
[Fact] [Fact]
public void Set() { 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); 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", ""); 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); 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", ""); 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); 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", ""); 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); Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql);
int incrv = 10; int incrv = 10;
sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); 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); 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", ""); 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); 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", ""); 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); 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", ""); 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); 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(); var id = g.mysql.Insert<TestEnumUpdateTb>().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity();
Assert.True(id > 0); Assert.True(id > 0);
sql = g.mysql.Update<TestEnumUpdateTb>().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ToSql().Replace("\r\n", ""); 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); 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(); 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); 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", ""); 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); 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(); 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); Assert.Equal(TestEnumUpdateTbType.str1, g.mysql.Select<TestEnumUpdateTb>().Where(a => a.id == id).First()?.type);
} }
[Fact] [Fact]
public void SetRaw() { 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); 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", ""); 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); Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql);
} }
[Fact] [Fact]
public void Where() { 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); 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", ""); 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); Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (id = ?id)", sql);
var item = new Topic { Id = 1, Title = "newtitle" }; var item = new Topic { Id = 1, Title = "newtitle" };
sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql); Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql);
var items = new List<Topic>(); 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 }); 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", ""); 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); 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) 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", ""); .Set(a => a.type, TestEnumUpdateTbType.sum211).ToSql().Replace("\r\n", "");
Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0 AND `type` = 'str1')", sql); Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0 AND `type` = 'str1')", sql);
} }
[Fact] [Fact]
public void WhereExists() { public void WhereExists()
{
} }
[Fact] [Fact]
public void ExecuteAffrows() { public void ExecuteAffrows()
{
} }
[Fact] [Fact]
public void ExecuteUpdated() { public void ExecuteUpdated()
{
} }
[Fact] [Fact]
public void AsTable() { 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.Null(g.mysql.Update<Topic>().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='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 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 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)", g.mysql.Update<Topic>(new { id = 1 }).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 System.Numerics;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySqlMapType { namespace FreeSql.Tests.MySqlMapType
public class EnumTest { {
class EnumTestMap { public class EnumTest
public Guid id { get; set; } {
class EnumTestMap
{
public Guid id { get; set; }
[Column(MapType = typeof(string))] [Column(MapType = typeof(string))]
public ToStringMapEnum enum_to_string { get; set; } public ToStringMapEnum enum_to_string { get; set; }
[Column(MapType = typeof(string))] [Column(MapType = typeof(string))]
public ToStringMapEnum? enumnullable_to_string { get; set; } public ToStringMapEnum? enumnullable_to_string { get; set; }
[Column(MapType = typeof(int))] [Column(MapType = typeof(int))]
public ToStringMapEnum enum_to_int { get; set; } public ToStringMapEnum enum_to_int { get; set; }
[Column(MapType = typeof(int?))] [Column(MapType = typeof(int?))]
public ToStringMapEnum? enumnullable_to_int { get; set; } public ToStringMapEnum? enumnullable_to_int { get; set; }
} }
public enum ToStringMapEnum { , abc, } public enum ToStringMapEnum { , abc, }
[Fact] [Fact]
public void EnumToString() { public void EnumToString()
//insert {
var orm = g.mysql; //insert
var item = new EnumTestMap { }; var orm = g.mysql;
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); var item = new EnumTestMap { };
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
Assert.NotNull(find); var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.Equal(item.id, find.id); Assert.NotNull(find);
Assert.Equal(item.enum_to_string, find.enum_to_string); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_string); 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 }; item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string); Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); Assert.Equal(ToStringMapEnum.abc, find.enum_to_string);
//update all //update all
item.enum_to_string = ToStringMapEnum.; item.enum_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string); Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string); Assert.Equal(ToStringMapEnum., find.enum_to_string);
item.enum_to_string = ToStringMapEnum.; item.enum_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_string, find.enum_to_string); Assert.Equal(item.enum_to_string, find.enum_to_string);
Assert.Equal(ToStringMapEnum., find.enum_to_string); Assert.Equal(ToStringMapEnum., find.enum_to_string);
//update set //update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_string); 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()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); Assert.Equal(ToStringMapEnum.abc, find.enum_to_string);
//delete //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(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.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()); Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
} }
[Fact] [Fact]
public void EnumNullableToString() { public void EnumNullableToString()
//insert {
var orm = g.mysql; //insert
var item = new EnumTestMap { }; var orm = g.mysql;
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); var item = new EnumTestMap { };
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
Assert.NotNull(find); var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.Equal(item.id, find.id); Assert.NotNull(find);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_string); Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Null(find.enumnullable_to_string);
item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum. }; item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum. };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); Assert.Equal(ToStringMapEnum., find.enumnullable_to_string);
//update all //update all
item.enumnullable_to_string = ToStringMapEnum.; item.enumnullable_to_string = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); Assert.Equal(ToStringMapEnum., find.enumnullable_to_string);
item.enumnullable_to_string = null; item.enumnullable_to_string = null;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string);
Assert.Null(find.enumnullable_to_string); Assert.Null(find.enumnullable_to_string);
//update set //update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); 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.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()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_string == null).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_string); Assert.Null(find.enumnullable_to_string);
//delete //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(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.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()); Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
} }
[Fact] [Fact]
public void EnumToInt() { public void EnumToInt()
//insert {
var orm = g.mysql; //insert
var item = new EnumTestMap { }; var orm = g.mysql;
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); var item = new EnumTestMap { };
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
Assert.NotNull(find); var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.Equal(item.id, find.id); Assert.NotNull(find);
Assert.Equal(item.enum_to_int, find.enum_to_int); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_int); 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 }; item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int); Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); Assert.Equal(ToStringMapEnum.abc, find.enum_to_int);
//update all //update all
item.enum_to_int = ToStringMapEnum.; item.enum_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int); Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int); Assert.Equal(ToStringMapEnum., find.enum_to_int);
item.enum_to_int = ToStringMapEnum.; item.enum_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enum_to_int, find.enum_to_int); Assert.Equal(item.enum_to_int, find.enum_to_int);
Assert.Equal(ToStringMapEnum., find.enum_to_int); Assert.Equal(ToStringMapEnum., find.enum_to_int);
//update set //update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum., find.enum_to_int); 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()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); Assert.Equal(ToStringMapEnum.abc, find.enum_to_int);
//delete //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(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.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()); Assert.Null(orm.Select<EnumTestMap>().Where(a => a.id == item.id).First());
} }
[Fact] [Fact]
public void EnumNullableToInt() { public void EnumNullableToInt()
//insert {
var orm = g.mysql; //insert
var item = new EnumTestMap { }; var orm = g.mysql;
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); var item = new EnumTestMap { };
var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows());
Assert.NotNull(find); var find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.Equal(item.id, find.id); Assert.NotNull(find);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_int); Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Null(find.enumnullable_to_int);
item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum. }; item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum. };
Assert.Equal(1, orm.Insert<EnumTestMap>().AppendData(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); Assert.Equal(ToStringMapEnum., find.enumnullable_to_int);
//update all //update all
item.enumnullable_to_int = ToStringMapEnum.; item.enumnullable_to_int = ToStringMapEnum.;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); Assert.Equal(ToStringMapEnum., find.enumnullable_to_int);
item.enumnullable_to_int = null; item.enumnullable_to_int = null;
Assert.Equal(1, orm.Update<EnumTestMap>().SetSource(item).ExecuteAffrows()); 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()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int);
Assert.Null(find.enumnullable_to_int); Assert.Null(find.enumnullable_to_int);
//update set //update set
Assert.Equal(1, orm.Update<EnumTestMap>().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); 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.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()); 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(); find = orm.Select<EnumTestMap>().Where(a => a.id == item.id && a.enumnullable_to_int == null).First();
Assert.NotNull(find); Assert.NotNull(find);
Assert.Equal(item.id, find.id); Assert.Equal(item.id, find.id);
Assert.Null(find.enumnullable_to_int); Assert.Null(find.enumnullable_to_int);
//delete //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(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.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()); 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 System;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySql { namespace FreeSql.Tests.MySql
public class MySqlAdoTest { {
[Fact] public class MySqlAdoTest
public void Pool() { {
var t1 = g.mysql.Ado.MasterPool.StatisticsFullily; [Fact]
} public void Pool()
{
var t1 = g.mysql.Ado.MasterPool.StatisticsFullily;
}
[Fact] [Fact]
public void SlavePools() { public void SlavePools()
var t2 = g.mysql.Ado.SlavePools.Count; {
} var t2 = g.mysql.Ado.SlavePools.Count;
}
[Fact] [Fact]
public void ExecuteReader() { public void ExecuteReader()
{
}
[Fact]
public void ExecuteArray() {
}
[Fact]
public void ExecuteNonQuery() {
}
[Fact]
public void ExecuteScalar() {
}
[Fact] }
public void Query() { [Fact]
var t3 = g.mysql.Ado.Query<xxx>("select * from song"); 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 { [Fact]
public int Id { get; set; } public void Query()
public string Path { get; set; } {
public string Title2 { get; set; } 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 System.Text;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySql { namespace FreeSql.Tests.MySql
public class MySqlCodeFirstTest { {
public class MySqlCodeFirstTest
{
[Fact] [Fact]
public void _字段() { public void _字段()
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<2>(); {
g.mysql.CodeFirst.SyncStructure<2>(); var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<2>();
g.mysql.CodeFirst.SyncStructure<2>();
var item = new 2 { var item = new 2
= "测试标题", {
= DateTime.Now = "测试标题",
}; = DateTime.Now
Assert.Equal(1, g.mysql.Insert<2>().AppendData(item).ExecuteAffrows()); };
Assert.NotEqual(Guid.Empty, item.); Assert.Equal(1, g.mysql.Insert<2>().AppendData(item).ExecuteAffrows());
var item2 = g.mysql.Select<2>().Where(a => a. == item.).First(); Assert.NotEqual(Guid.Empty, item.);
Assert.NotNull(item2); var item2 = g.mysql.Select<2>().Where(a => a. == item.).First();
Assert.Equal(item., item2.); Assert.NotNull(item2);
Assert.Equal(item., item2.); Assert.Equal(item., item2.);
} Assert.Equal(item., item2.);
class 2 { }
[Column(IsPrimary = true)] class 2
public Guid { get; set; } {
[Column(IsPrimary = true)]
public Guid { get; set; }
public string { get; set; } public string { get; set; }
public DateTime { get; set; } public DateTime { get; set; }
} }
[Fact] [Fact]
public void AddUniques() { public void AddUniques()
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<AddUniquesInfo>(); {
g.mysql.CodeFirst.SyncStructure<AddUniquesInfo>(); var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<AddUniquesInfo>();
} g.mysql.CodeFirst.SyncStructure<AddUniquesInfo>();
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")] }
class AddUniquesInfo { [Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
public Guid id { get; set; } class AddUniquesInfo
[Column(Unique = "uk_phone")] {
public string phone { get; set; } public Guid id { get; set; }
[Column(Unique = "uk_phone")]
public string phone { get; set; }
[Column(Unique = "uk_group_index, uk_group_index22")] [Column(Unique = "uk_group_index, uk_group_index22")]
public string group { get; set; } public string group { get; set; }
[Column(Unique = "uk_group_index")] [Column(Unique = "uk_group_index")]
public int index { get; set; } public int index { get; set; }
[Column(Unique = "uk_group_index22")] [Column(Unique = "uk_group_index22")]
public string index22 { get; set; } public string index22 { get; set; }
} }
[Fact] [Fact]
public void AddField() { public void AddField()
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TopicAddField>(); {
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")] [Table(Name = "TopicAddField", OldName = "xxxtb.TopicAddField")]
public class TopicAddField { public class TopicAddField
[Column(IsIdentity = true)] {
public int? Id { get; set; } [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")] [Column(DbType = "varchar(200) not null", OldName = "title")]
public string title222 { get; set; } = "10"; public string title222 { get; set; } = "10";
[Column(IsIgnore = true)] [Column(IsIgnore = true)]
public DateTime ct { get; set; } = DateTime.Now; public DateTime ct { get; set; } = DateTime.Now;
} }
[Fact] [Fact]
public void GetComparisonDDLStatements() { public void GetComparisonDDLStatements()
{
var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TableAllType>(); var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<TableAllType>();
if (string.IsNullOrEmpty(sql) == false) { if (string.IsNullOrEmpty(sql) == false)
Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` ( {
Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` (
`Id` INT(11) NOT NULL AUTO_INCREMENT, `Id` INT(11) NOT NULL AUTO_INCREMENT,
`testFieldBool` BIT(1) NOT NULL, `testFieldBool` BIT(1) NOT NULL,
`testFieldSByte` TINYINT(3) NOT NULL, `testFieldSByte` TINYINT(3) NOT NULL,
@ -126,352 +137,363 @@ namespace FreeSql.Tests.MySql {
PRIMARY KEY (`Id`) PRIMARY KEY (`Id`)
) Engine=InnoDB; ) Engine=InnoDB;
", sql); ", sql);
} }
sql = g.mysql.CodeFirst.GetComparisonDDLStatements<Tb_alltype>(); sql = g.mysql.CodeFirst.GetComparisonDDLStatements<Tb_alltype>();
} }
IInsert<TableAllType> insert => g.mysql.Insert<TableAllType>(); IInsert<TableAllType> insert => g.mysql.Insert<TableAllType>();
ISelect<TableAllType> select => g.mysql.Select<TableAllType>(); ISelect<TableAllType> select => g.mysql.Select<TableAllType>();
[Fact] [Fact]
public void CurdAllField() { public void CurdAllField()
var item = new TableAllType { }; {
item.Id = (int)insert.AppendData(item).ExecuteIdentity(); var item = new TableAllType { };
item.Id = (int)insert.AppendData(item).ExecuteIdentity();
var newitem = select.Where(a => a.Id == item.Id).ToOne();
var newitem = select.Where(a => a.Id == item.Id).ToOne();
var item2 = new TableAllType {
testFieldBool = true, var item2 = new TableAllType
testFieldBoolNullable = true, {
testFieldByte = 255, testFieldBool = true,
testFieldByteNullable = 127, testFieldBoolNullable = true,
testFieldBytes = Encoding.UTF8.GetBytes("我是中国人"), testFieldByte = 255,
testFieldDateTime = DateTime.Now, testFieldByteNullable = 127,
testFieldDateTimeNullable = DateTime.Now.AddHours(-1), testFieldBytes = Encoding.UTF8.GetBytes("我是中国人"),
testFieldDecimal = 99.99M, testFieldDateTime = DateTime.Now,
testFieldDecimalNullable = 99.98M, testFieldDateTimeNullable = DateTime.Now.AddHours(-1),
testFieldDouble = 999.99, testFieldDecimal = 99.99M,
testFieldDoubleNullable = 999.98, testFieldDecimalNullable = 99.98M,
testFieldEnum1 = TableAllTypeEnumType1.e5, testFieldDouble = 999.99,
testFieldEnum1Nullable = TableAllTypeEnumType1.e3, testFieldDoubleNullable = 999.98,
testFieldEnum2 = TableAllTypeEnumType2.f2, testFieldEnum1 = TableAllTypeEnumType1.e5,
testFieldEnum2Nullable = TableAllTypeEnumType2.f3, testFieldEnum1Nullable = TableAllTypeEnumType1.e3,
testFieldFloat = 19.99F, testFieldEnum2 = TableAllTypeEnumType2.f2,
testFieldFloatNullable = 19.98F, testFieldEnum2Nullable = TableAllTypeEnumType2.f3,
testFieldGuid = Guid.NewGuid(), testFieldFloat = 19.99F,
testFieldGuidNullable = Guid.NewGuid(), testFieldFloatNullable = 19.98F,
testFieldInt = int.MaxValue, testFieldGuid = Guid.NewGuid(),
testFieldIntNullable = int.MinValue, testFieldGuidNullable = Guid.NewGuid(),
testFieldLineString = new MygisLineString(new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }), testFieldInt = int.MaxValue,
testFieldLong = long.MaxValue, testFieldIntNullable = int.MinValue,
testFieldMultiLineString = new MygisMultiLineString(new[] { testFieldLineString = new MygisLineString(new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }),
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }, testFieldLong = long.MaxValue,
new[] { new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 100) } }), testFieldMultiLineString = new MygisMultiLineString(new[] {
testFieldMultiPoint = new MygisMultiPoint(new[] { new MygisCoordinate2D(11, 11), new MygisCoordinate2D(51, 11) }), new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) },
testFieldMultiPolygon = new MygisMultiPolygon(new[] { new[] { new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 100) } }),
new MygisPolygon(new[] { testFieldMultiPoint = new MygisMultiPoint(new[] { new MygisCoordinate2D(11, 11), new MygisCoordinate2D(51, 11) }),
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, testFieldMultiPolygon = new MygisMultiPolygon(new[] {
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) },
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), new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
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) }, testFieldPoint = new MygisPoint(99, 99),
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, 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, new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
testFieldSByteNullable = 99, new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }),
testFieldShort = short.MaxValue, testFieldSByte = 100,
testFieldShortNullable = short.MinValue, testFieldSByteNullable = 99,
testFieldString = "我是中国人string", testFieldShort = short.MaxValue,
testFieldTimeSpan = TimeSpan.FromSeconds(999), testFieldShortNullable = short.MinValue,
testFieldTimeSpanNullable = TimeSpan.FromSeconds(60), testFieldString = "我是中国人string",
testFieldUInt = uint.MaxValue, testFieldTimeSpan = TimeSpan.FromSeconds(999),
testFieldUIntNullable = uint.MinValue, testFieldTimeSpanNullable = TimeSpan.FromSeconds(60),
testFieldULong = ulong.MaxValue, testFieldUInt = uint.MaxValue,
testFieldULongNullable = ulong.MinValue, testFieldUIntNullable = uint.MinValue,
testFieldUShort = ushort.MaxValue, testFieldULong = ulong.MaxValue,
testFieldUShortNullable = ushort.MinValue, testFieldULongNullable = ulong.MinValue,
testFielLongNullable = long.MinValue testFieldUShort = ushort.MaxValue,
}; testFieldUShortNullable = ushort.MinValue,
item2.Id = (int)insert.AppendData(item2).ExecuteIdentity(); testFielLongNullable = long.MinValue
var newitem2 = select.Where(a => a.Id == item2.Id).ToOne(); };
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")] [JsonObject(MemberSerialization.OptIn), Table(Name = "tb_alltype")]
public partial class Tb_alltype { public partial class Tb_alltype
{
[JsonProperty, Column(Name = "Id", DbType = "int(11)", IsPrimary = true, IsIdentity = true)] [JsonProperty, Column(Name = "Id", DbType = "int(11)", IsPrimary = true, IsIdentity = true)]
public int Id { get; set; } public int Id { get; set; }
[JsonProperty, Column(Name = "testFieldBool", DbType = "bit(1)")] [JsonProperty, Column(Name = "testFieldBool", DbType = "bit(1)")]
public bool TestFieldBool { get; set; } public bool TestFieldBool { get; set; }
[JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit(1)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit(1)", IsNullable = true)]
public bool? TestFieldBoolNullable { get; set; } public bool? TestFieldBoolNullable { get; set; }
[JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint(3) unsigned")] [JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint(3) unsigned")]
public byte TestFieldByte { get; set; } public byte TestFieldByte { get; set; }
[JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint(3) unsigned", IsNullable = true)] [JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint(3) unsigned", IsNullable = true)]
public byte? TestFieldByteNullable { get; set; } public byte? TestFieldByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldBytes", DbType = "varbinary(255)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldBytes", DbType = "varbinary(255)", IsNullable = true)]
public byte[] TestFieldBytes { get; set; } public byte[] TestFieldBytes { get; set; }
[JsonProperty, Column(Name = "testFieldDateTime", DbType = "datetime")] [JsonProperty, Column(Name = "testFieldDateTime", DbType = "datetime")]
public DateTime TestFieldDateTime { get; set; } public DateTime TestFieldDateTime { get; set; }
[JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)] [JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)]
public DateTime? TestFieldDateTimeNullable { get; set; } public DateTime? TestFieldDateTimeNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDecimal", DbType = "decimal(10,2)")] [JsonProperty, Column(Name = "testFieldDecimal", DbType = "decimal(10,2)")]
public decimal TestFieldDecimal { get; set; } public decimal TestFieldDecimal { get; set; }
[JsonProperty, Column(Name = "testFieldDecimalNullable", DbType = "decimal(10,2)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldDecimalNullable", DbType = "decimal(10,2)", IsNullable = true)]
public decimal? TestFieldDecimalNullable { get; set; } public decimal? TestFieldDecimalNullable { get; set; }
[JsonProperty, Column(Name = "testFieldDouble", DbType = "double")] [JsonProperty, Column(Name = "testFieldDouble", DbType = "double")]
public double TestFieldDouble { get; set; } public double TestFieldDouble { get; set; }
[JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "double", IsNullable = true)] [JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "double", IsNullable = true)]
public double? TestFieldDoubleNullable { get; set; } public double? TestFieldDoubleNullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1", DbType = "enum('E1','E2','E3','E5')")] [JsonProperty, Column(Name = "testFieldEnum1", DbType = "enum('E1','E2','E3','E5')")]
public Tb_alltypeTESTFIELDENUM1 TestFieldEnum1 { get; set; } public Tb_alltypeTESTFIELDENUM1 TestFieldEnum1 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "enum('E1','E2','E3','E5')", IsNullable = true)] [JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "enum('E1','E2','E3','E5')", IsNullable = true)]
public Tb_alltypeTESTFIELDENUM1NULLABLE? TestFieldEnum1Nullable { get; set; } public Tb_alltypeTESTFIELDENUM1NULLABLE? TestFieldEnum1Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2", DbType = "set('F1','F2','F3')")] [JsonProperty, Column(Name = "testFieldEnum2", DbType = "set('F1','F2','F3')")]
public Tb_alltypeTESTFIELDENUM2 TestFieldEnum2 { get; set; } public Tb_alltypeTESTFIELDENUM2 TestFieldEnum2 { get; set; }
[JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "set('F1','F2','F3')", IsNullable = true)] [JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "set('F1','F2','F3')", IsNullable = true)]
public Tb_alltypeTESTFIELDENUM2NULLABLE? TestFieldEnum2Nullable { get; set; } public Tb_alltypeTESTFIELDENUM2NULLABLE? TestFieldEnum2Nullable { get; set; }
[JsonProperty, Column(Name = "testFieldFloat", DbType = "float")] [JsonProperty, Column(Name = "testFieldFloat", DbType = "float")]
public float TestFieldFloat { get; set; } public float TestFieldFloat { get; set; }
[JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "float", IsNullable = true)] [JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "float", IsNullable = true)]
public float? TestFieldFloatNullable { get; set; } public float? TestFieldFloatNullable { get; set; }
[JsonProperty, Column(Name = "testFieldGuid", DbType = "char(36)")] [JsonProperty, Column(Name = "testFieldGuid", DbType = "char(36)")]
public Guid TestFieldGuid { get; set; } public Guid TestFieldGuid { get; set; }
[JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "char(36)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "char(36)", IsNullable = true)]
public Guid? TestFieldGuidNullable { get; set; } public Guid? TestFieldGuidNullable { get; set; }
[JsonProperty, Column(Name = "testFieldInt", DbType = "int(11)")] [JsonProperty, Column(Name = "testFieldInt", DbType = "int(11)")]
public int TestFieldInt { get; set; } public int TestFieldInt { get; set; }
[JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int(11)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int(11)", IsNullable = true)]
public int? TestFieldIntNullable { get; set; } public int? TestFieldIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldLineString", DbType = "linestring", IsNullable = true)] [JsonProperty, Column(Name = "testFieldLineString", DbType = "linestring", IsNullable = true)]
public MygisGeometry TestFieldLineString { get; set; } public MygisGeometry TestFieldLineString { get; set; }
[JsonProperty, Column(Name = "testFieldLong", DbType = "bigint(20)")] [JsonProperty, Column(Name = "testFieldLong", DbType = "bigint(20)")]
public long TestFieldLong { get; set; } public long TestFieldLong { get; set; }
[JsonProperty, Column(Name = "testFieldMultiLineString", DbType = "multilinestring", IsNullable = true)] [JsonProperty, Column(Name = "testFieldMultiLineString", DbType = "multilinestring", IsNullable = true)]
public MygisGeometry TestFieldMultiLineString { get; set; } public MygisGeometry TestFieldMultiLineString { get; set; }
[JsonProperty, Column(Name = "testFieldMultiPoint", DbType = "multipoint", IsNullable = true)] [JsonProperty, Column(Name = "testFieldMultiPoint", DbType = "multipoint", IsNullable = true)]
public MygisGeometry TestFieldMultiPoint { get; set; } public MygisGeometry TestFieldMultiPoint { get; set; }
[JsonProperty, Column(Name = "testFieldMultiPolygon", DbType = "multipolygon", IsNullable = true)] [JsonProperty, Column(Name = "testFieldMultiPolygon", DbType = "multipolygon", IsNullable = true)]
public MygisGeometry TestFieldMultiPolygon { get; set; } public MygisGeometry TestFieldMultiPolygon { get; set; }
[JsonProperty, Column(Name = "testFieldPoint", DbType = "point", IsNullable = true)] [JsonProperty, Column(Name = "testFieldPoint", DbType = "point", IsNullable = true)]
public MygisGeometry TestFieldPoint { get; set; } public MygisGeometry TestFieldPoint { get; set; }
[JsonProperty, Column(Name = "testFieldPolygon", DbType = "polygon", IsNullable = true)] [JsonProperty, Column(Name = "testFieldPolygon", DbType = "polygon", IsNullable = true)]
public MygisGeometry TestFieldPolygon { get; set; } public MygisGeometry TestFieldPolygon { get; set; }
[JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint(3)")] [JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint(3)")]
public sbyte TestFieldSByte { get; set; } public sbyte TestFieldSByte { get; set; }
[JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint(3)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint(3)", IsNullable = true)]
public sbyte? TestFieldSByteNullable { get; set; } public sbyte? TestFieldSByteNullable { get; set; }
[JsonProperty, Column(Name = "testFieldShort", DbType = "smallint(6)")] [JsonProperty, Column(Name = "testFieldShort", DbType = "smallint(6)")]
public short TestFieldShort { get; set; } public short TestFieldShort { get; set; }
[JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint(6)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint(6)", IsNullable = true)]
public short? TestFieldShortNullable { get; set; } public short? TestFieldShortNullable { get; set; }
[JsonProperty, Column(Name = "testFieldString", DbType = "varchar(255)", IsNullable = true)] [JsonProperty, Column(Name = "testFieldString", DbType = "varchar(255)", IsNullable = true)]
public string TestFieldString { get; set; } public string TestFieldString { get; set; }
[JsonProperty, Column(Name = "testFieldTimeSpan", DbType = "time")] [JsonProperty, Column(Name = "testFieldTimeSpan", DbType = "time")]
public TimeSpan TestFieldTimeSpan { get; set; } public TimeSpan TestFieldTimeSpan { get; set; }
[JsonProperty, Column(Name = "testFieldTimeSpanNullable", DbType = "time", IsNullable = true)] [JsonProperty, Column(Name = "testFieldTimeSpanNullable", DbType = "time", IsNullable = true)]
public TimeSpan? TestFieldTimeSpanNullable { get; set; } public TimeSpan? TestFieldTimeSpanNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUInt", DbType = "int(10) unsigned")] [JsonProperty, Column(Name = "testFieldUInt", DbType = "int(10) unsigned")]
public uint TestFieldUInt { get; set; } public uint TestFieldUInt { get; set; }
[JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int(10) unsigned", IsNullable = true)] [JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int(10) unsigned", IsNullable = true)]
public uint? TestFieldUIntNullable { get; set; } public uint? TestFieldUIntNullable { get; set; }
[JsonProperty, Column(Name = "testFieldULong", DbType = "bigint(20) unsigned")] [JsonProperty, Column(Name = "testFieldULong", DbType = "bigint(20) unsigned")]
public ulong TestFieldULong { get; set; } public ulong TestFieldULong { get; set; }
[JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint(20) unsigned", IsNullable = true)] [JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint(20) unsigned", IsNullable = true)]
public ulong? TestFieldULongNullable { get; set; } public ulong? TestFieldULongNullable { get; set; }
[JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint(5) unsigned")] [JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint(5) unsigned")]
public ushort TestFieldUShort { get; set; } public ushort TestFieldUShort { get; set; }
[JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint(5) unsigned", IsNullable = true)] [JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint(5) unsigned", IsNullable = true)]
public ushort? TestFieldUShortNullable { get; set; } public ushort? TestFieldUShortNullable { get; set; }
[JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint(20)", IsNullable = true)] [JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint(20)", IsNullable = true)]
public long? TestFielLongNullable { get; set; } public long? TestFielLongNullable { get; set; }
internal static IFreeSql mysql => null; internal static IFreeSql mysql => null;
public static FreeSql.ISelect<Tb_alltype> Select => mysql.Select<Tb_alltype>(); public static FreeSql.ISelect<Tb_alltype> Select => mysql.Select<Tb_alltype>();
public static long Delete(int Id) { public static long Delete(int Id)
var affrows = mysql.Delete<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows(); {
return affrows; var affrows = mysql.Delete<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows();
} return affrows;
}
/// <summary> /// <summary>
/// 保存或添加,如果主键有值则尝试 Update如果影响的行为 0 则尝试 Insert /// 保存或添加,如果主键有值则尝试 Update如果影响的行为 0 则尝试 Insert
/// </summary> /// </summary>
public void Save() { public void Save()
if (this.Id != default(int)) { {
var affrows = mysql.Update<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows(); if (this.Id != default(int))
if (affrows > 0) return; {
} var affrows = mysql.Update<Tb_alltype>().Where(a => a.Id == Id).ExecuteAffrows();
this.Id = (int)mysql.Insert<Tb_alltype>().AppendData(this).ExecuteIdentity(); if (affrows > 0) return;
} }
this.Id = (int)mysql.Insert<Tb_alltype>().AppendData(this).ExecuteIdentity();
}
} }
public enum Tb_alltypeTESTFIELDENUM1 { public enum Tb_alltypeTESTFIELDENUM1
E1 = 1, E2, E3, E5 {
} E1 = 1, E2, E3, E5
public enum Tb_alltypeTESTFIELDENUM1NULLABLE { }
E1 = 1, E2, E3, E5 public enum Tb_alltypeTESTFIELDENUM1NULLABLE
} {
[Flags] E1 = 1, E2, E3, E5
public enum Tb_alltypeTESTFIELDENUM2 : long { }
F1 = 1, F2 = 2, F3 = 4 [Flags]
} public enum Tb_alltypeTESTFIELDENUM2 : long
[Flags] {
public enum Tb_alltypeTESTFIELDENUM2NULLABLE : long { F1 = 1, F2 = 2, F3 = 4
F1 = 1, F2 = 2, F3 = 4 }
} [Flags]
public enum Tb_alltypeTESTFIELDENUM2NULLABLE : long
{
F1 = 1, F2 = 2, F3 = 4
}
[Table(Name = "tb_alltype")] [Table(Name = "tb_alltype")]
class TableAllType { class TableAllType
[Column(IsIdentity = true, IsPrimary = true)] {
public int Id { get; set; } [Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public bool testFieldBool { get; set; }
public sbyte testFieldSByte { get; set; } public bool testFieldBool { get; set; }
public short testFieldShort { get; set; } public sbyte testFieldSByte { get; set; }
public int testFieldInt { get; set; } public short testFieldShort { get; set; }
public long testFieldLong { get; set; } public int testFieldInt { get; set; }
public byte testFieldByte { get; set; } public long testFieldLong { get; set; }
public ushort testFieldUShort { get; set; } public byte testFieldByte { get; set; }
public uint testFieldUInt { get; set; } public ushort testFieldUShort { get; set; }
public ulong testFieldULong { get; set; } public uint testFieldUInt { get; set; }
public double testFieldDouble { get; set; } public ulong testFieldULong { get; set; }
public float testFieldFloat { get; set; } public double testFieldDouble { get; set; }
public decimal testFieldDecimal { get; set; } public float testFieldFloat { get; set; }
public TimeSpan testFieldTimeSpan { get; set; } public decimal testFieldDecimal { get; set; }
public DateTime testFieldDateTime { get; set; } public TimeSpan testFieldTimeSpan { get; set; }
public byte[] testFieldBytes { get; set; } public DateTime testFieldDateTime { get; set; }
public string testFieldString { get; set; } public byte[] testFieldBytes { get; set; }
public Guid testFieldGuid { get; set; } public string testFieldString { get; set; }
public Guid testFieldGuid { get; set; }
public bool? testFieldBoolNullable { get; set; }
public sbyte? testFieldSByteNullable { get; set; } public bool? testFieldBoolNullable { get; set; }
public short? testFieldShortNullable { get; set; } public sbyte? testFieldSByteNullable { get; set; }
public int? testFieldIntNullable { get; set; } public short? testFieldShortNullable { get; set; }
public long? testFielLongNullable { get; set; } public int? testFieldIntNullable { get; set; }
public byte? testFieldByteNullable { get; set; } public long? testFielLongNullable { get; set; }
public ushort? testFieldUShortNullable { get; set; } public byte? testFieldByteNullable { get; set; }
public uint? testFieldUIntNullable { get; set; } public ushort? testFieldUShortNullable { get; set; }
public ulong? testFieldULongNullable { get; set; } public uint? testFieldUIntNullable { get; set; }
public double? testFieldDoubleNullable { get; set; } public ulong? testFieldULongNullable { get; set; }
public float? testFieldFloatNullable { get; set; } public double? testFieldDoubleNullable { get; set; }
public decimal? testFieldDecimalNullable { get; set; } public float? testFieldFloatNullable { get; set; }
public TimeSpan? testFieldTimeSpanNullable { get; set; } public decimal? testFieldDecimalNullable { get; set; }
public DateTime? testFieldDateTimeNullable { get; set; } public TimeSpan? testFieldTimeSpanNullable { get; set; }
public Guid? testFieldGuidNullable { get; set; } public DateTime? testFieldDateTimeNullable { get; set; }
public Guid? testFieldGuidNullable { get; set; }
public MygisPoint testFieldPoint { get; set; }
public MygisLineString testFieldLineString { get; set; } public MygisPoint testFieldPoint { get; set; }
public MygisPolygon testFieldPolygon { get; set; } public MygisLineString testFieldLineString { get; set; }
public MygisMultiPoint testFieldMultiPoint { get; set; } public MygisPolygon testFieldPolygon { get; set; }
public MygisMultiLineString testFieldMultiLineString { get; set; } public MygisMultiPoint testFieldMultiPoint { get; set; }
public MygisMultiPolygon testFieldMultiPolygon { get; set; } public MygisMultiLineString testFieldMultiLineString { get; set; }
public MygisMultiPolygon testFieldMultiPolygon { get; set; }
public TableAllTypeEnumType1 testFieldEnum1 { get; set; }
public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } public TableAllTypeEnumType1 testFieldEnum1 { get; set; }
public TableAllTypeEnumType2 testFieldEnum2 { get; set; } public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; }
public TableAllTypeEnumType2? testFieldEnum2Nullable { 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 } 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