mirror of
https://github.com/nsnail/FreeSql.git
synced 2025-06-18 20:08:15 +08:00
源代码改用vs默认格式化
This commit is contained in:
@ -8,207 +8,230 @@ using BenchmarkDotNet.Running;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
//using SqlSugar;
|
||||
|
||||
namespace FreeSql.Bechmarker {
|
||||
namespace FreeSql.Bechmarker
|
||||
{
|
||||
|
||||
public class Program {
|
||||
public static void Main(string[] args) {
|
||||
var summaryInsert = BenchmarkRunner.Run<OrmVsInsert>();
|
||||
var summarySelect = BenchmarkRunner.Run<OrmVsSelect>();
|
||||
var summaryUpdate = BenchmarkRunner.Run<OrmVsUpdate>();
|
||||
}
|
||||
}
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var summaryInsert = BenchmarkRunner.Run<OrmVsInsert>();
|
||||
var summarySelect = BenchmarkRunner.Run<OrmVsSelect>();
|
||||
var summaryUpdate = BenchmarkRunner.Run<OrmVsUpdate>();
|
||||
}
|
||||
}
|
||||
|
||||
public class Orm {
|
||||
public static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=20")
|
||||
//.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=20")
|
||||
.UseAutoSyncStructure(false)
|
||||
.UseNoneCommandParameter(true)
|
||||
//.UseConfigEntityFromDbFirst(true)
|
||||
.Build();
|
||||
public class Orm
|
||||
{
|
||||
public static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=20")
|
||||
//.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=20")
|
||||
.UseAutoSyncStructure(false)
|
||||
.UseNoneCommandParameter(true)
|
||||
//.UseConfigEntityFromDbFirst(true)
|
||||
.Build();
|
||||
|
||||
//public static SqlSugarClient sugar {
|
||||
// get => new SqlSugarClient(new ConnectionConfig() {
|
||||
// //不欺负,让连接池100个最小
|
||||
// ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20",
|
||||
// DbType = DbType.SqlServer,
|
||||
// //ConnectionString = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=20;Max Pool Size=20",
|
||||
// //DbType = DbType.MySql,
|
||||
// IsAutoCloseConnection = true,
|
||||
// InitKeyType = InitKeyType.Attribute
|
||||
// });
|
||||
//}
|
||||
}
|
||||
class SongContext : DbContext {
|
||||
public DbSet<Song> Songs { get; set; }
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
|
||||
optionsBuilder.UseSqlServer(@"Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=21;Max Pool Size=21");
|
||||
//optionsBuilder.UseMySql("Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=21;Max Pool Size=21");
|
||||
}
|
||||
}
|
||||
//public static SqlSugarClient sugar {
|
||||
// get => new SqlSugarClient(new ConnectionConfig() {
|
||||
// //不欺负,让连接池100个最小
|
||||
// ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20",
|
||||
// DbType = DbType.SqlServer,
|
||||
// //ConnectionString = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=20;Max Pool Size=20",
|
||||
// //DbType = DbType.MySql,
|
||||
// IsAutoCloseConnection = true,
|
||||
// InitKeyType = InitKeyType.Attribute
|
||||
// });
|
||||
//}
|
||||
}
|
||||
class SongContext : DbContext
|
||||
{
|
||||
public DbSet<Song> Songs { get; set; }
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
optionsBuilder.UseSqlServer(@"Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=21;Max Pool Size=21");
|
||||
//optionsBuilder.UseMySql("Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=21;Max Pool Size=21");
|
||||
}
|
||||
}
|
||||
|
||||
[CoreJob]
|
||||
[RPlotExporter, RankColumn]
|
||||
public class OrmVsInsert {
|
||||
public IEnumerable<Song> songs;
|
||||
[CoreJob]
|
||||
[RPlotExporter, RankColumn]
|
||||
public class OrmVsInsert
|
||||
{
|
||||
public IEnumerable<Song> songs;
|
||||
|
||||
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
|
||||
public int size;
|
||||
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
|
||||
public int size;
|
||||
|
||||
[GlobalSetup]
|
||||
public void Setup() {
|
||||
Orm.fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag));
|
||||
//Orm.sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag));
|
||||
//sugar创建表失败:SqlSugar.SqlSugarException: Sequence contains no elements
|
||||
[GlobalSetup]
|
||||
public void Setup()
|
||||
{
|
||||
Orm.fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag));
|
||||
//Orm.sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag));
|
||||
//sugar创建表失败:SqlSugar.SqlSugarException: Sequence contains no elements
|
||||
|
||||
//测试前清空数据
|
||||
Orm.fsql.Delete<Song>().Where(a => a.Id > 0).ExecuteAffrows();
|
||||
//Orm.sugar.Deleteable<Song>().Where(a => a.Id > 0).ExecuteCommand();
|
||||
Orm.fsql.Ado.ExecuteNonQuery("delete from efcore_song");
|
||||
//测试前清空数据
|
||||
Orm.fsql.Delete<Song>().Where(a => a.Id > 0).ExecuteAffrows();
|
||||
//Orm.sugar.Deleteable<Song>().Where(a => a.Id > 0).ExecuteCommand();
|
||||
Orm.fsql.Ado.ExecuteNonQuery("delete from efcore_song");
|
||||
|
||||
songs = Enumerable.Range(0, size).Select(a => new Song {
|
||||
Create_time = DateTime.Now,
|
||||
Is_deleted = false,
|
||||
Title = $"Insert_{a}",
|
||||
Url = $"Url_{a}"
|
||||
});
|
||||
songs = Enumerable.Range(0, size).Select(a => new Song
|
||||
{
|
||||
Create_time = DateTime.Now,
|
||||
Is_deleted = false,
|
||||
Title = $"Insert_{a}",
|
||||
Url = $"Url_{a}"
|
||||
});
|
||||
|
||||
//预热
|
||||
Orm.fsql.Insert(songs.First()).ExecuteAffrows();
|
||||
//Orm.sugar.Insertable(songs.First()).ExecuteCommand();
|
||||
using (var db = new SongContext()) {
|
||||
//db.Configuration.AutoDetectChangesEnabled = false;
|
||||
db.Songs.AddRange(songs.First());
|
||||
db.SaveChanges();
|
||||
}
|
||||
}
|
||||
//预热
|
||||
Orm.fsql.Insert(songs.First()).ExecuteAffrows();
|
||||
//Orm.sugar.Insertable(songs.First()).ExecuteCommand();
|
||||
using (var db = new SongContext())
|
||||
{
|
||||
//db.Configuration.AutoDetectChangesEnabled = false;
|
||||
db.Songs.AddRange(songs.First());
|
||||
db.SaveChanges();
|
||||
}
|
||||
}
|
||||
|
||||
[Benchmark]
|
||||
public int FreeSqlInsert() => Orm.fsql.Insert(songs).ExecuteAffrows();
|
||||
[Benchmark]
|
||||
public int FreeSqlInsert() => Orm.fsql.Insert(songs).ExecuteAffrows();
|
||||
|
||||
//[Benchmark]
|
||||
//public int SqlSugarInsert() => Orm.sugar.Insertable(songs.ToArray()).ExecuteCommand();
|
||||
//[Benchmark]
|
||||
//public int SqlSugarInsert() => Orm.sugar.Insertable(songs.ToArray()).ExecuteCommand();
|
||||
|
||||
[Benchmark]
|
||||
public int EfCoreInsert() {
|
||||
using (var db = new SongContext()) {
|
||||
//db.Configuration.AutoDetectChangesEnabled = false;
|
||||
db.Songs.AddRange(songs.ToArray());
|
||||
return db.SaveChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
[Benchmark]
|
||||
public int EfCoreInsert()
|
||||
{
|
||||
using (var db = new SongContext())
|
||||
{
|
||||
//db.Configuration.AutoDetectChangesEnabled = false;
|
||||
db.Songs.AddRange(songs.ToArray());
|
||||
return db.SaveChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[CoreJob]
|
||||
[RPlotExporter, RankColumn]
|
||||
public class OrmVsUpdate {
|
||||
public List<Song> songs;
|
||||
[CoreJob]
|
||||
[RPlotExporter, RankColumn]
|
||||
public class OrmVsUpdate
|
||||
{
|
||||
public List<Song> songs;
|
||||
|
||||
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
|
||||
public int size;
|
||||
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
|
||||
public int size;
|
||||
|
||||
[GlobalSetup]
|
||||
public void Setup() {
|
||||
songs = Orm.fsql.Select<Song>().Limit(size).ToList();
|
||||
}
|
||||
[GlobalSetup]
|
||||
public void Setup()
|
||||
{
|
||||
songs = Orm.fsql.Select<Song>().Limit(size).ToList();
|
||||
}
|
||||
|
||||
[Benchmark]
|
||||
public int FreeSqlUpdate() => Orm.fsql.Update<Song>().SetSource(songs).ExecuteAffrows();
|
||||
[Benchmark]
|
||||
public int FreeSqlUpdate() => Orm.fsql.Update<Song>().SetSource(songs).ExecuteAffrows();
|
||||
|
||||
//[Benchmark]
|
||||
//public int SqlSugarUpdate() => Orm.sugar.Updateable(songs).ExecuteCommand();
|
||||
//[Benchmark]
|
||||
//public int SqlSugarUpdate() => Orm.sugar.Updateable(songs).ExecuteCommand();
|
||||
|
||||
[Benchmark]
|
||||
public int EfCoreUpdate() {
|
||||
using (var db = new SongContext()) {
|
||||
//db.Configuration.AutoDetectChangesEnabled = false;
|
||||
db.Songs.UpdateRange(songs.ToArray());
|
||||
return db.SaveChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
[Benchmark]
|
||||
public int EfCoreUpdate()
|
||||
{
|
||||
using (var db = new SongContext())
|
||||
{
|
||||
//db.Configuration.AutoDetectChangesEnabled = false;
|
||||
db.Songs.UpdateRange(songs.ToArray());
|
||||
return db.SaveChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[CoreJob]
|
||||
[RPlotExporter, RankColumn]
|
||||
public class OrmVsSelect {
|
||||
[CoreJob]
|
||||
[RPlotExporter, RankColumn]
|
||||
public class OrmVsSelect
|
||||
{
|
||||
|
||||
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
|
||||
public int size;
|
||||
[Params(1, 500, 1000, 5000, 10000, 50000, 100000)]
|
||||
public int size;
|
||||
|
||||
[GlobalSetup]
|
||||
public void Setup() {
|
||||
|
||||
}
|
||||
[GlobalSetup]
|
||||
public void Setup()
|
||||
{
|
||||
|
||||
[Benchmark]
|
||||
public List<Song> FreeSqlSelect() => Orm.fsql.Select<Song>().Limit(size).ToList();
|
||||
}
|
||||
|
||||
//[Benchmark]
|
||||
//public List<Song> SqlSugarSelect() => Orm.sugar.Queryable<Song>().Take(size).ToList();
|
||||
[Benchmark]
|
||||
public List<Song> FreeSqlSelect() => Orm.fsql.Select<Song>().Limit(size).ToList();
|
||||
|
||||
[Benchmark]
|
||||
public List<Song> EfCoreSelect() {
|
||||
using (var db = new SongContext()) {
|
||||
return db.Songs.Take(size).AsNoTracking().ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
//[Benchmark]
|
||||
//public List<Song> SqlSugarSelect() => Orm.sugar.Queryable<Song>().Take(size).ToList();
|
||||
|
||||
[FreeSql.DataAnnotations.Table(Name = "freesql_song")]
|
||||
//[SugarTable("sugar_song")]
|
||||
[Table("efcore_song")]
|
||||
public class Song {
|
||||
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
|
||||
//[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
[Key]
|
||||
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||
public int Id { get; set; }
|
||||
public DateTime? Create_time { get; set; }
|
||||
public bool? Is_deleted { get; set; }
|
||||
public string Title { get; set; }
|
||||
public string Url { get; set; }
|
||||
[Benchmark]
|
||||
public List<Song> EfCoreSelect()
|
||||
{
|
||||
using (var db = new SongContext())
|
||||
{
|
||||
return db.Songs.Take(size).AsNoTracking().ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual ICollection<Tag> Tags { get; set; }
|
||||
}
|
||||
[FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")]
|
||||
//[SugarTable("sugar_song_tag")]
|
||||
[Table("efcore_song_tag")]
|
||||
public class Song_tag {
|
||||
public int Song_id { get; set; }
|
||||
//[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual Song Song { get; set; }
|
||||
[FreeSql.DataAnnotations.Table(Name = "freesql_song")]
|
||||
//[SugarTable("sugar_song")]
|
||||
[Table("efcore_song")]
|
||||
public class Song
|
||||
{
|
||||
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
|
||||
//[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
[Key]
|
||||
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||
public int Id { get; set; }
|
||||
public DateTime? Create_time { get; set; }
|
||||
public bool? Is_deleted { get; set; }
|
||||
public string Title { get; set; }
|
||||
public string Url { get; set; }
|
||||
|
||||
public int Tag_id { get; set; }
|
||||
//[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual Tag Tag { get; set; }
|
||||
}
|
||||
[FreeSql.DataAnnotations.Table(Name = "freesql_tag")]
|
||||
//[SugarTable("sugar_tag")]
|
||||
[Table("efcore_tag")]
|
||||
public class Tag {
|
||||
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
|
||||
//[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
[Key]
|
||||
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||
public int Id { get; set; }
|
||||
public int? Parent_id { get; set; }
|
||||
//[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual Tag Parent { get; set; }
|
||||
//[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual ICollection<Tag> Tags { get; set; }
|
||||
}
|
||||
[FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")]
|
||||
//[SugarTable("sugar_song_tag")]
|
||||
[Table("efcore_song_tag")]
|
||||
public class Song_tag
|
||||
{
|
||||
public int Song_id { get; set; }
|
||||
//[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual Song Song { get; set; }
|
||||
|
||||
public decimal? Ddd { get; set; }
|
||||
public string Name { get; set; }
|
||||
public int Tag_id { get; set; }
|
||||
//[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual Tag Tag { get; set; }
|
||||
}
|
||||
[FreeSql.DataAnnotations.Table(Name = "freesql_tag")]
|
||||
//[SugarTable("sugar_tag")]
|
||||
[Table("efcore_tag")]
|
||||
public class Tag
|
||||
{
|
||||
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
|
||||
//[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
[Key]
|
||||
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||
public int Id { get; set; }
|
||||
public int? Parent_id { get; set; }
|
||||
//[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual Tag Parent { get; set; }
|
||||
|
||||
//[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual ICollection<Song> Songs { get; set; }
|
||||
//[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual ICollection<Tag> Tags { get; set; }
|
||||
}
|
||||
public decimal? Ddd { get; set; }
|
||||
public string Name { get; set; }
|
||||
|
||||
//[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual ICollection<Song> Songs { get; set; }
|
||||
//[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual ICollection<Tag> Tags { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -5,237 +5,251 @@ using System.Threading.Tasks;
|
||||
using FreeSql;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace dbcontext_01.Controllers {
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class ValuesController : ControllerBase {
|
||||
|
||||
IFreeSql _orm;
|
||||
SongContext _songContext;
|
||||
public ValuesController(SongContext songContext,
|
||||
IFreeSql orm1, IFreeSql orm2,
|
||||
IFreeSql<long> orm3
|
||||
) {
|
||||
_songContext = songContext;
|
||||
_orm = orm1;
|
||||
namespace dbcontext_01.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class ValuesController : ControllerBase
|
||||
{
|
||||
|
||||
IFreeSql _orm;
|
||||
SongContext _songContext;
|
||||
public ValuesController(SongContext songContext,
|
||||
IFreeSql orm1, IFreeSql orm2,
|
||||
IFreeSql<long> orm3
|
||||
)
|
||||
{
|
||||
_songContext = songContext;
|
||||
_orm = orm1;
|
||||
|
||||
}
|
||||
|
||||
// GET api/values
|
||||
[HttpGet]
|
||||
async public Task<string> Get()
|
||||
{
|
||||
|
||||
long id = 0;
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
var repos2Song = _orm.GetRepository<Song, int>();
|
||||
repos2Song.Where(a => a.Id > 10).ToList();
|
||||
//查询结果,进入 states
|
||||
|
||||
var song = new Song { };
|
||||
repos2Song.Insert(song);
|
||||
id = song.Id;
|
||||
|
||||
}
|
||||
|
||||
// GET api/values
|
||||
[HttpGet]
|
||||
async public Task<string> Get() {
|
||||
var adds = Enumerable.Range(0, 100)
|
||||
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
|
||||
.ToList();
|
||||
//创建一堆无主键值
|
||||
|
||||
long id = 0;
|
||||
repos2Song.Insert(adds);
|
||||
|
||||
try {
|
||||
for (var a = 0; a < 10; a++)
|
||||
adds[a].Title = "dkdkdkdk" + a;
|
||||
|
||||
var repos2Song = _orm.GetRepository<Song, int>();
|
||||
repos2Song.Where(a => a.Id > 10).ToList();
|
||||
//查询结果,进入 states
|
||||
repos2Song.Update(adds);
|
||||
//批量修改
|
||||
|
||||
var song = new Song { };
|
||||
repos2Song.Insert(song);
|
||||
id = song.Id;
|
||||
repos2Song.Delete(adds.Skip(10).Take(20).ToList());
|
||||
//批量删除,10-20 元素的主键值会被清除
|
||||
|
||||
var adds = Enumerable.Range(0, 100)
|
||||
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
|
||||
.ToList();
|
||||
//创建一堆无主键值
|
||||
adds.Last().Url = "skldfjlksdjglkjjcccc";
|
||||
repos2Song.Update(adds.Last());
|
||||
|
||||
repos2Song.Insert(adds);
|
||||
adds.First().Url = "skldfjlksdjglkjjcccc";
|
||||
repos2Song.Update(adds.First());
|
||||
|
||||
for (var a = 0; a < 10; a++)
|
||||
adds[a].Title = "dkdkdkdk" + a;
|
||||
|
||||
repos2Song.Update(adds);
|
||||
//批量修改
|
||||
var ctx = _songContext;
|
||||
var tag = new Tag
|
||||
{
|
||||
Name = "testaddsublist",
|
||||
Tags = new[] {
|
||||
new Tag { Name = "sub1" },
|
||||
new Tag { Name = "sub2" },
|
||||
new Tag {
|
||||
Name = "sub3",
|
||||
Tags = new[] {
|
||||
new Tag { Name = "sub3_01" }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
ctx.Tags.Add(tag);
|
||||
|
||||
repos2Song.Delete(adds.Skip(10).Take(20).ToList());
|
||||
//批量删除,10-20 元素的主键值会被清除
|
||||
|
||||
adds.Last().Url = "skldfjlksdjglkjjcccc";
|
||||
repos2Song.Update(adds.Last());
|
||||
ctx.UnitOfWork.GetOrBeginTransaction();
|
||||
|
||||
adds.First().Url = "skldfjlksdjglkjjcccc";
|
||||
repos2Song.Update(adds.First());
|
||||
var tagAsync = new Tag
|
||||
{
|
||||
Name = "testaddsublist",
|
||||
Tags = new[] {
|
||||
new Tag { Name = "sub1" },
|
||||
new Tag { Name = "sub2" },
|
||||
new Tag {
|
||||
Name = "sub3",
|
||||
Tags = new[] {
|
||||
new Tag { Name = "sub3_01" }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
await ctx.Tags.AddAsync(tagAsync);
|
||||
|
||||
|
||||
var ctx = _songContext;
|
||||
var tag = new Tag {
|
||||
Name = "testaddsublist",
|
||||
Tags = new[] {
|
||||
new Tag { Name = "sub1" },
|
||||
new Tag { Name = "sub2" },
|
||||
new Tag {
|
||||
Name = "sub3",
|
||||
Tags = new[] {
|
||||
new Tag { Name = "sub3_01" }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
ctx.Tags.Add(tag);
|
||||
ctx.Songs.Select.Where(a => a.Id > 10).ToList();
|
||||
//查询结果,进入 states
|
||||
|
||||
song = new Song { };
|
||||
//可插入的 song
|
||||
|
||||
ctx.UnitOfWork.GetOrBeginTransaction();
|
||||
ctx.Songs.Add(song);
|
||||
id = song.Id;
|
||||
//因有自增类型,立即开启事务执行SQL,返回自增值
|
||||
|
||||
var tagAsync = new Tag {
|
||||
Name = "testaddsublist",
|
||||
Tags = new[] {
|
||||
new Tag { Name = "sub1" },
|
||||
new Tag { Name = "sub2" },
|
||||
new Tag {
|
||||
Name = "sub3",
|
||||
Tags = new[] {
|
||||
new Tag { Name = "sub3_01" }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
await ctx.Tags.AddAsync(tagAsync);
|
||||
adds = Enumerable.Range(0, 100)
|
||||
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
|
||||
.ToList();
|
||||
//创建一堆无主键值
|
||||
|
||||
ctx.Songs.AddRange(adds);
|
||||
//立即执行,将自增值赋给 adds 所有元素,因为有自增类型,如果其他类型,指定传入主键值,不会立即执行
|
||||
|
||||
ctx.Songs.Select.Where(a => a.Id > 10).ToList();
|
||||
//查询结果,进入 states
|
||||
for (var a = 0; a < 10; a++)
|
||||
adds[a].Title = "dkdkdkdk" + a;
|
||||
|
||||
song = new Song { };
|
||||
//可插入的 song
|
||||
ctx.Songs.UpdateRange(adds);
|
||||
//批量修改,进入队列
|
||||
|
||||
ctx.Songs.Add(song);
|
||||
id = song.Id;
|
||||
//因有自增类型,立即开启事务执行SQL,返回自增值
|
||||
ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList());
|
||||
//批量删除,进入队列,完成时 10-20 元素的主键值会被清除
|
||||
|
||||
adds = Enumerable.Range(0, 100)
|
||||
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
|
||||
.ToList();
|
||||
//创建一堆无主键值
|
||||
//ctx.Songs.Update(adds.First());
|
||||
|
||||
ctx.Songs.AddRange(adds);
|
||||
//立即执行,将自增值赋给 adds 所有元素,因为有自增类型,如果其他类型,指定传入主键值,不会立即执行
|
||||
adds.Last().Url = "skldfjlksdjglkjjcccc";
|
||||
ctx.Songs.Update(adds.Last());
|
||||
|
||||
for (var a = 0; a < 10; a++)
|
||||
adds[a].Title = "dkdkdkdk" + a;
|
||||
adds.First().Url = "skldfjlksdjglkjjcccc";
|
||||
ctx.Songs.Update(adds.First());
|
||||
|
||||
ctx.Songs.UpdateRange(adds);
|
||||
//批量修改,进入队列
|
||||
//单条修改 urls 的值,进入队列
|
||||
|
||||
ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList());
|
||||
//批量删除,进入队列,完成时 10-20 元素的主键值会被清除
|
||||
//throw new Exception("回滚");
|
||||
|
||||
//ctx.Songs.Update(adds.First());
|
||||
//ctx.Songs.Select.First();
|
||||
//这里做一个查询,会立即打包【执行队列】,避免没有提交的数据,影响查询结果
|
||||
|
||||
adds.Last().Url = "skldfjlksdjglkjjcccc";
|
||||
ctx.Songs.Update(adds.Last());
|
||||
ctx.SaveChanges();
|
||||
//打包【执行队列】,提交事务
|
||||
|
||||
adds.First().Url = "skldfjlksdjglkjjcccc";
|
||||
ctx.Songs.Update(adds.First());
|
||||
|
||||
//单条修改 urls 的值,进入队列
|
||||
using (var uow = _orm.CreateUnitOfWork())
|
||||
{
|
||||
|
||||
//throw new Exception("回滚");
|
||||
var reposSong = uow.GetRepository<Song, int>();
|
||||
reposSong.Where(a => a.Id > 10).ToList();
|
||||
//查询结果,进入 states
|
||||
|
||||
//ctx.Songs.Select.First();
|
||||
//这里做一个查询,会立即打包【执行队列】,避免没有提交的数据,影响查询结果
|
||||
song = new Song { };
|
||||
reposSong.Insert(song);
|
||||
id = song.Id;
|
||||
|
||||
ctx.SaveChanges();
|
||||
//打包【执行队列】,提交事务
|
||||
adds = Enumerable.Range(0, 100)
|
||||
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
|
||||
.ToList();
|
||||
//创建一堆无主键值
|
||||
|
||||
reposSong.Insert(adds);
|
||||
|
||||
using (var uow = _orm.CreateUnitOfWork()) {
|
||||
for (var a = 0; a < 10; a++)
|
||||
adds[a].Title = "dkdkdkdk" + a;
|
||||
|
||||
var reposSong = uow.GetRepository<Song, int>();
|
||||
reposSong.Where(a => a.Id > 10).ToList();
|
||||
//查询结果,进入 states
|
||||
reposSong.Update(adds);
|
||||
//批量修改
|
||||
|
||||
song = new Song { };
|
||||
reposSong.Insert(song);
|
||||
id = song.Id;
|
||||
reposSong.Delete(adds.Skip(10).Take(20).ToList());
|
||||
//批量删除,10-20 元素的主键值会被清除
|
||||
|
||||
adds = Enumerable.Range(0, 100)
|
||||
.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
|
||||
.ToList();
|
||||
//创建一堆无主键值
|
||||
adds.Last().Url = "skldfjlksdjglkjjcccc";
|
||||
reposSong.Update(adds.Last());
|
||||
|
||||
reposSong.Insert(adds);
|
||||
adds.First().Url = "skldfjlksdjglkjjcccc";
|
||||
reposSong.Update(adds.First());
|
||||
|
||||
for (var a = 0; a < 10; a++)
|
||||
adds[a].Title = "dkdkdkdk" + a;
|
||||
uow.Commit();
|
||||
}
|
||||
|
||||
reposSong.Update(adds);
|
||||
//批量修改
|
||||
|
||||
reposSong.Delete(adds.Skip(10).Take(20).ToList());
|
||||
//批量删除,10-20 元素的主键值会被清除
|
||||
|
||||
adds.Last().Url = "skldfjlksdjglkjjcccc";
|
||||
reposSong.Update(adds.Last());
|
||||
//using (var ctx = new SongContext()) {
|
||||
|
||||
adds.First().Url = "skldfjlksdjglkjjcccc";
|
||||
reposSong.Update(adds.First());
|
||||
// var song = new Song { };
|
||||
// await ctx.Songs.AddAsync(song);
|
||||
// id = song.Id;
|
||||
|
||||
uow.Commit();
|
||||
}
|
||||
// var adds = Enumerable.Range(0, 100)
|
||||
// .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
|
||||
// .ToList();
|
||||
// await ctx.Songs.AddRangeAsync(adds);
|
||||
|
||||
// for (var a = 0; a < adds.Count; a++)
|
||||
// adds[a].Title = "dkdkdkdk" + a;
|
||||
|
||||
// ctx.Songs.UpdateRange(adds);
|
||||
|
||||
//using (var ctx = new SongContext()) {
|
||||
// ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList());
|
||||
|
||||
// var song = new Song { };
|
||||
// await ctx.Songs.AddAsync(song);
|
||||
// id = song.Id;
|
||||
// //ctx.Songs.Update(adds.First());
|
||||
|
||||
// var adds = Enumerable.Range(0, 100)
|
||||
// .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" })
|
||||
// .ToList();
|
||||
// await ctx.Songs.AddRangeAsync(adds);
|
||||
// adds.Last().Url = "skldfjlksdjglkjjcccc";
|
||||
// ctx.Songs.Update(adds.Last());
|
||||
|
||||
// for (var a = 0; a < adds.Count; a++)
|
||||
// adds[a].Title = "dkdkdkdk" + a;
|
||||
// //throw new Exception("回滚");
|
||||
|
||||
// ctx.Songs.UpdateRange(adds);
|
||||
// await ctx.SaveChangesAsync();
|
||||
//}
|
||||
}
|
||||
catch
|
||||
{
|
||||
var item = await _orm.Select<Song>().Where(a => a.Id == id).FirstAsync();
|
||||
|
||||
// ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList());
|
||||
throw;
|
||||
}
|
||||
|
||||
// //ctx.Songs.Update(adds.First());
|
||||
var item22 = await _orm.Select<Song>().Where(a => a.Id == id).FirstAsync();
|
||||
var item33 = await _orm.Select<Song>().Where(a => a.Id > id).ToListAsync();
|
||||
|
||||
// adds.Last().Url = "skldfjlksdjglkjjcccc";
|
||||
// ctx.Songs.Update(adds.Last());
|
||||
return item22.Id.ToString();
|
||||
}
|
||||
|
||||
// //throw new Exception("回滚");
|
||||
// GET api/values/5
|
||||
[HttpGet("{id}")]
|
||||
public ActionResult<string> Get(int id)
|
||||
{
|
||||
return "value";
|
||||
}
|
||||
|
||||
// await ctx.SaveChangesAsync();
|
||||
//}
|
||||
} catch {
|
||||
var item = await _orm.Select<Song>().Where(a => a.Id == id).FirstAsync();
|
||||
// POST api/values
|
||||
[HttpPost]
|
||||
public void Post([FromBody] string value)
|
||||
{
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
// PUT api/values/5
|
||||
[HttpPut("{id}")]
|
||||
public void Put(int id, [FromBody] string value)
|
||||
{
|
||||
}
|
||||
|
||||
var item22 = await _orm.Select<Song>().Where(a => a.Id == id).FirstAsync();
|
||||
var item33 = await _orm.Select<Song>().Where(a => a.Id > id).ToListAsync();
|
||||
|
||||
return item22.Id.ToString();
|
||||
}
|
||||
|
||||
// GET api/values/5
|
||||
[HttpGet("{id}")]
|
||||
public ActionResult<string> Get(int id) {
|
||||
return "value";
|
||||
}
|
||||
|
||||
// POST api/values
|
||||
[HttpPost]
|
||||
public void Post([FromBody] string value) {
|
||||
}
|
||||
|
||||
// PUT api/values/5
|
||||
[HttpPut("{id}")]
|
||||
public void Put(int id, [FromBody] string value) {
|
||||
}
|
||||
|
||||
// DELETE api/values/5
|
||||
[HttpDelete("{id}")]
|
||||
public void Delete(int id) {
|
||||
}
|
||||
}
|
||||
// DELETE api/values/5
|
||||
[HttpDelete("{id}")]
|
||||
public void Delete(int id)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,50 +3,55 @@ using FreeSql.DataAnnotations;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace dbcontext_01 {
|
||||
namespace dbcontext_01
|
||||
{
|
||||
|
||||
public class SongContext : DbContext {
|
||||
public class SongContext : DbContext
|
||||
{
|
||||
|
||||
public DbSet<Song> Songs { get; set; }
|
||||
public DbSet<Tag> Tags { get; set; }
|
||||
public DbSet<Song> Songs { get; set; }
|
||||
public DbSet<Tag> Tags { get; set; }
|
||||
|
||||
//protected override void OnConfiguring(DbContextOptionsBuilder builder) {
|
||||
// builder.UseFreeSql(dbcontext_01.Startup.Fsql);
|
||||
//}
|
||||
}
|
||||
//protected override void OnConfiguring(DbContextOptionsBuilder builder) {
|
||||
// builder.UseFreeSql(dbcontext_01.Startup.Fsql);
|
||||
//}
|
||||
}
|
||||
|
||||
|
||||
public class Song {
|
||||
[Column(IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public DateTime? Create_time { get; set; }
|
||||
public bool? Is_deleted { get; set; }
|
||||
public string Title { get; set; }
|
||||
public string Url { get; set; }
|
||||
public class Song
|
||||
{
|
||||
[Column(IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public DateTime? Create_time { get; set; }
|
||||
public bool? Is_deleted { get; set; }
|
||||
public string Title { get; set; }
|
||||
public string Url { get; set; }
|
||||
|
||||
public virtual ICollection<Tag> Tags { get; set; }
|
||||
public virtual ICollection<Tag> Tags { get; set; }
|
||||
|
||||
[Column(IsVersion = true)]
|
||||
public long versionRow { get; set; }
|
||||
}
|
||||
public class Song_tag {
|
||||
public int Song_id { get; set; }
|
||||
public virtual Song Song { get; set; }
|
||||
[Column(IsVersion = true)]
|
||||
public long versionRow { get; set; }
|
||||
}
|
||||
public class Song_tag
|
||||
{
|
||||
public int Song_id { get; set; }
|
||||
public virtual Song Song { get; set; }
|
||||
|
||||
public int Tag_id { get; set; }
|
||||
public virtual Tag Tag { get; set; }
|
||||
}
|
||||
public int Tag_id { get; set; }
|
||||
public virtual Tag Tag { get; set; }
|
||||
}
|
||||
|
||||
public class Tag {
|
||||
[Column(IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public int? Parent_id { get; set; }
|
||||
public virtual Tag Parent { get; set; }
|
||||
public class Tag
|
||||
{
|
||||
[Column(IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public int? Parent_id { get; set; }
|
||||
public virtual Tag Parent { get; set; }
|
||||
|
||||
public decimal? Ddd { get; set; }
|
||||
public string Name { get; set; }
|
||||
public decimal? Ddd { get; set; }
|
||||
public string Name { get; set; }
|
||||
|
||||
public virtual ICollection<Song> Songs { get; set; }
|
||||
public virtual ICollection<Tag> Tags { get; set; }
|
||||
}
|
||||
public virtual ICollection<Song> Songs { get; set; }
|
||||
public virtual ICollection<Tag> Tags { get; set; }
|
||||
}
|
||||
}
|
||||
|
@ -17,51 +17,56 @@ namespace dbcontext_01
|
||||
public class Program
|
||||
{
|
||||
|
||||
public class Song {
|
||||
[Column(IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public string BigNumber { get; set; }
|
||||
public class Song
|
||||
{
|
||||
[Column(IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public string BigNumber { get; set; }
|
||||
|
||||
[Column(IsVersion = true)]//使用简单
|
||||
public long versionRow { get; set; }
|
||||
}
|
||||
[Column(IsVersion = true)]//使用简单
|
||||
public long versionRow { get; set; }
|
||||
}
|
||||
|
||||
public class SongContext : DbContext {
|
||||
public class SongContext : DbContext
|
||||
{
|
||||
|
||||
public DbSet<Song> Songs { get; set; }
|
||||
public DbSet<Song> Songs { get; set; }
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder builder) {
|
||||
builder.UseFreeSql(fsql);
|
||||
}
|
||||
}
|
||||
static IFreeSql fsql;
|
||||
public static void Main(string[] args) {
|
||||
fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\dd2.db;Pooling=true;Max Pool Size=10")
|
||||
.UseAutoSyncStructure(true)
|
||||
.UseLazyLoading(true)
|
||||
.UseNoneCommandParameter(true)
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder builder)
|
||||
{
|
||||
builder.UseFreeSql(fsql);
|
||||
}
|
||||
}
|
||||
static IFreeSql fsql;
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\dd2.db;Pooling=true;Max Pool Size=10")
|
||||
.UseAutoSyncStructure(true)
|
||||
.UseLazyLoading(true)
|
||||
.UseNoneCommandParameter(true)
|
||||
|
||||
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
|
||||
.Build();
|
||||
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
|
||||
.Build();
|
||||
|
||||
|
||||
using (var ctx = new SongContext()) {
|
||||
var song = new Song { BigNumber = "1000000000000000000" };
|
||||
ctx.Songs.Add(song);
|
||||
using (var ctx = new SongContext())
|
||||
{
|
||||
var song = new Song { BigNumber = "1000000000000000000" };
|
||||
ctx.Songs.Add(song);
|
||||
|
||||
ctx.Songs.Update(song);
|
||||
ctx.Songs.Update(song);
|
||||
|
||||
song.BigNumber = (BigInteger.Parse(song.BigNumber) + 1).ToString();
|
||||
ctx.Songs.Update(song);
|
||||
song.BigNumber = (BigInteger.Parse(song.BigNumber) + 1).ToString();
|
||||
ctx.Songs.Update(song);
|
||||
|
||||
ctx.SaveChanges();
|
||||
ctx.SaveChanges();
|
||||
|
||||
var sql = fsql.Update<Song>().SetSource(song).ToSql();
|
||||
}
|
||||
var sql = fsql.Update<Song>().SetSource(song).ToSql();
|
||||
}
|
||||
|
||||
CreateWebHostBuilder(args).Build().Run();
|
||||
}
|
||||
CreateWebHostBuilder(args).Build().Run();
|
||||
}
|
||||
|
||||
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
|
||||
WebHost.CreateDefaultBuilder(args)
|
||||
|
@ -1,27 +1,27 @@
|
||||
{
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:53030/",
|
||||
"sslPort": 0
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:53030/",
|
||||
"sslPort": 0
|
||||
}
|
||||
},
|
||||
"dbcontext_01": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"applicationUrl": "http://localhost:53031/"
|
||||
"profiles": {
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"dbcontext_01": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"applicationUrl": "http://localhost:53031/"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -19,93 +19,101 @@ namespace dbcontext_01
|
||||
{
|
||||
Configuration = configuration;
|
||||
|
||||
Fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document2.db;Pooling=true;Max Pool Size=10")
|
||||
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
|
||||
Fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document2.db;Pooling=true;Max Pool Size=10")
|
||||
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
|
||||
|
||||
//.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10")
|
||||
//.UseSyncStructureToUpper(true)
|
||||
//.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10")
|
||||
//.UseSyncStructureToUpper(true)
|
||||
|
||||
.UseAutoSyncStructure(true)
|
||||
.UseLazyLoading(true)
|
||||
.UseNoneCommandParameter(true)
|
||||
.UseAutoSyncStructure(true)
|
||||
.UseLazyLoading(true)
|
||||
.UseNoneCommandParameter(true)
|
||||
|
||||
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText),
|
||||
(cmd, log) => Trace.WriteLine(log)
|
||||
)
|
||||
.Build();
|
||||
Fsql.Aop.SyncStructureBefore = (s, e) => {
|
||||
Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName)));
|
||||
};
|
||||
Fsql.Aop.SyncStructureAfter = (s, e) => {
|
||||
Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName)) + " " + e.ElapsedMilliseconds + "ms\r\n" + e.Exception?.Message + e.Sql);
|
||||
};
|
||||
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText),
|
||||
(cmd, log) => Trace.WriteLine(log)
|
||||
)
|
||||
.Build();
|
||||
Fsql.Aop.SyncStructureBefore = (s, e) =>
|
||||
{
|
||||
Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName)));
|
||||
};
|
||||
Fsql.Aop.SyncStructureAfter = (s, e) =>
|
||||
{
|
||||
Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName)) + " " + e.ElapsedMilliseconds + "ms\r\n" + e.Exception?.Message + e.Sql);
|
||||
};
|
||||
|
||||
Fsql.Aop.CurdBefore = (s, e) => {
|
||||
Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + ", " + e.Sql);
|
||||
};
|
||||
Fsql.Aop.CurdAfter = (s, e) => {
|
||||
Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + " " + e.ElapsedMilliseconds + "ms, " + e.Sql);
|
||||
};
|
||||
Fsql.Aop.CurdBefore = (s, e) =>
|
||||
{
|
||||
Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + ", " + e.Sql);
|
||||
};
|
||||
Fsql.Aop.CurdAfter = (s, e) =>
|
||||
{
|
||||
Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + " " + e.ElapsedMilliseconds + "ms, " + e.Sql);
|
||||
};
|
||||
|
||||
Fsql2 = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document222.db;Pooling=true;Max Pool Size=10")
|
||||
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
|
||||
.UseAutoSyncStructure(true)
|
||||
.UseLazyLoading(true)
|
||||
Fsql2 = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document222.db;Pooling=true;Max Pool Size=10")
|
||||
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10")
|
||||
.UseAutoSyncStructure(true)
|
||||
.UseLazyLoading(true)
|
||||
|
||||
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText),
|
||||
(cmd, log) => Trace.WriteLine(log)
|
||||
)
|
||||
.Build<long>();
|
||||
}
|
||||
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText),
|
||||
(cmd, log) => Trace.WriteLine(log)
|
||||
)
|
||||
.Build<long>();
|
||||
}
|
||||
|
||||
enum MySql { }
|
||||
enum PgSql { }
|
||||
enum MySql { }
|
||||
enum PgSql { }
|
||||
|
||||
public IConfiguration Configuration { get; }
|
||||
public static IFreeSql Fsql { get; private set; }
|
||||
public static IFreeSql<long> Fsql2 { get; private set; }
|
||||
public IConfiguration Configuration { get; }
|
||||
public static IFreeSql Fsql { get; private set; }
|
||||
public static IFreeSql<long> Fsql2 { get; private set; }
|
||||
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddMvc();
|
||||
services.AddSwaggerGen(options => {
|
||||
options.SwaggerDoc("v1", new Info {
|
||||
Version = "v1",
|
||||
Title = "FreeSql.DbContext API"
|
||||
});
|
||||
//options.IncludeXmlComments(xmlPath);
|
||||
});
|
||||
services.AddMvc();
|
||||
services.AddSwaggerGen(options =>
|
||||
{
|
||||
options.SwaggerDoc("v1", new Info
|
||||
{
|
||||
Version = "v1",
|
||||
Title = "FreeSql.DbContext API"
|
||||
});
|
||||
//options.IncludeXmlComments(xmlPath);
|
||||
});
|
||||
|
||||
|
||||
|
||||
services.AddSingleton<IFreeSql>(Fsql);
|
||||
services.AddSingleton<IFreeSql<long>>(Fsql2);
|
||||
services.AddFreeDbContext<SongContext>(options => options.UseFreeSql(Fsql));
|
||||
services.AddSingleton<IFreeSql>(Fsql);
|
||||
services.AddSingleton<IFreeSql<long>>(Fsql2);
|
||||
services.AddFreeDbContext<SongContext>(options => options.UseFreeSql(Fsql));
|
||||
|
||||
|
||||
var sql1 = Fsql.Update<Song>(1).Set(a => a.Id + 10).ToSql();
|
||||
var sql2 = Fsql.Update<Song>(1).Set(a => a.Title + 10).ToSql();
|
||||
var sql3 = Fsql.Update<Song>(1).Set(a => a.Create_time.Value.AddHours(1)).ToSql();
|
||||
}
|
||||
var sql1 = Fsql.Update<Song>(1).Set(a => a.Id + 10).ToSql();
|
||||
var sql2 = Fsql.Update<Song>(1).Set(a => a.Title + 10).ToSql();
|
||||
var sql3 = Fsql.Update<Song>(1).Set(a => a.Create_time.Value.AddHours(1)).ToSql();
|
||||
}
|
||||
|
||||
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
|
||||
Console.InputEncoding = Encoding.GetEncoding("GB2312");
|
||||
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
|
||||
{
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
|
||||
Console.InputEncoding = Encoding.GetEncoding("GB2312");
|
||||
|
||||
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
|
||||
loggerFactory.AddDebug();
|
||||
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
|
||||
loggerFactory.AddDebug();
|
||||
|
||||
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
|
||||
app.UseDeveloperExceptionPage();
|
||||
app.UseMvc();
|
||||
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
|
||||
app.UseDeveloperExceptionPage();
|
||||
app.UseMvc();
|
||||
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(c => {
|
||||
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
|
||||
});
|
||||
}
|
||||
}
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(c =>
|
||||
{
|
||||
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Debug",
|
||||
"System": "Information",
|
||||
"Microsoft": "Information"
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Debug",
|
||||
"System": "Information",
|
||||
"Microsoft": "Information"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
|
@ -2,18 +2,22 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
|
||||
namespace efcore_to_freesql.DBContexts {
|
||||
namespace efcore_to_freesql.DBContexts
|
||||
{
|
||||
|
||||
public class BaseDBContext : DbContext {
|
||||
public class BaseDBContext : DbContext
|
||||
{
|
||||
|
||||
public static IFreeSql Fsql { get; set; }
|
||||
public static IFreeSql Fsql { get; set; }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder) {
|
||||
base.OnModelCreating(modelBuilder);
|
||||
Fsql.CodeFirst.ConfigEntity(modelBuilder.Model); //ͬ<><CDAC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
}
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
|
||||
optionsBuilder.UseSqlite(@"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10");
|
||||
}
|
||||
}
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
Fsql.CodeFirst.ConfigEntity(modelBuilder.Model); //ͬ<><CDAC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
}
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
optionsBuilder.UseSqlite(@"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,18 +1,21 @@
|
||||
using efcore_to_freesql.Entitys;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace efcore_to_freesql.DBContexts {
|
||||
namespace efcore_to_freesql.DBContexts
|
||||
{
|
||||
|
||||
public class Topic1Context : BaseDBContext {
|
||||
public class Topic1Context : BaseDBContext
|
||||
{
|
||||
|
||||
public DbSet<Topic1> Topic1s { get; set; }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder) {
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
|
||||
modelBuilder.Entity<Topic1>().ToTable("topic1_sss").HasKey(a => a.Id);
|
||||
modelBuilder.Entity<Topic1>().Property(a => a.Id).HasColumnName("topic1_id").ValueGeneratedOnAdd();
|
||||
modelBuilder.Entity<Topic1>().ToTable("topic1_sss").HasKey(a => a.Id);
|
||||
modelBuilder.Entity<Topic1>().Property(a => a.Id).HasColumnName("topic1_id").ValueGeneratedOnAdd();
|
||||
|
||||
base.OnModelCreating(modelBuilder);
|
||||
}
|
||||
}
|
||||
base.OnModelCreating(modelBuilder);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,18 +1,21 @@
|
||||
using efcore_to_freesql.Entitys;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace efcore_to_freesql.DBContexts {
|
||||
namespace efcore_to_freesql.DBContexts
|
||||
{
|
||||
|
||||
public class Topic2Context : BaseDBContext {
|
||||
public class Topic2Context : BaseDBContext
|
||||
{
|
||||
|
||||
public DbSet<Topic2> Topic2s { get; set; }
|
||||
public DbSet<Topic2> Topic2s { get; set; }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder) {
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
|
||||
modelBuilder.Entity<Topic2>().ToTable("topic2_sss");
|
||||
modelBuilder.Entity<Topic2>().Property(a => a.Id).HasColumnName("topic2_id");
|
||||
modelBuilder.Entity<Topic2>().ToTable("topic2_sss");
|
||||
modelBuilder.Entity<Topic2>().Property(a => a.Id).HasColumnName("topic2_id");
|
||||
|
||||
base.OnModelCreating(modelBuilder);
|
||||
}
|
||||
}
|
||||
base.OnModelCreating(modelBuilder);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,6 +1,7 @@
|
||||
using System;
|
||||
|
||||
namespace efcore_to_freesql.Entitys {
|
||||
namespace efcore_to_freesql.Entitys
|
||||
{
|
||||
|
||||
public class Topic1
|
||||
{
|
||||
|
@ -2,7 +2,8 @@ using System;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace efcore_to_freesql.Entitys {
|
||||
namespace efcore_to_freesql.Entitys
|
||||
{
|
||||
|
||||
public class Topic2
|
||||
{
|
||||
|
@ -6,60 +6,67 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public static class CodeFirstExtensions {
|
||||
public static class CodeFirstExtensions
|
||||
{
|
||||
|
||||
public static void ConfigEntity(this ICodeFirst codeFirst, IModel efmodel) {
|
||||
public static void ConfigEntity(this ICodeFirst codeFirst, IModel efmodel)
|
||||
{
|
||||
|
||||
foreach (var type in efmodel.GetEntityTypes()) {
|
||||
foreach (var type in efmodel.GetEntityTypes())
|
||||
{
|
||||
|
||||
codeFirst.ConfigEntity(type.ClrType, a => {
|
||||
codeFirst.ConfigEntity(type.ClrType, a =>
|
||||
{
|
||||
|
||||
//表名
|
||||
var relationalTableName = type.FindAnnotation("Relational:TableName");
|
||||
if (relationalTableName != null)
|
||||
a.Name(relationalTableName.Value?.ToString() ?? type.ClrType.Name);
|
||||
//表名
|
||||
var relationalTableName = type.FindAnnotation("Relational:TableName");
|
||||
if (relationalTableName != null)
|
||||
a.Name(relationalTableName.Value?.ToString() ?? type.ClrType.Name);
|
||||
|
||||
foreach (var prop in type.GetProperties()) {
|
||||
foreach (var prop in type.GetProperties())
|
||||
{
|
||||
|
||||
var freeProp = a.Property(prop.Name);
|
||||
var freeProp = a.Property(prop.Name);
|
||||
|
||||
//列名
|
||||
var relationalColumnName = prop.FindAnnotation("Relational:ColumnName");
|
||||
if (relationalColumnName != null)
|
||||
freeProp.Name(relationalColumnName.Value?.ToString() ?? prop.Name);
|
||||
//列名
|
||||
var relationalColumnName = prop.FindAnnotation("Relational:ColumnName");
|
||||
if (relationalColumnName != null)
|
||||
freeProp.Name(relationalColumnName.Value?.ToString() ?? prop.Name);
|
||||
|
||||
//主键
|
||||
freeProp.IsPrimary(prop.IsPrimaryKey());
|
||||
//主键
|
||||
freeProp.IsPrimary(prop.IsPrimaryKey());
|
||||
|
||||
//自增
|
||||
freeProp.IsIdentity(
|
||||
prop.ValueGenerated == ValueGenerated.Never ||
|
||||
prop.ValueGenerated == ValueGenerated.OnAdd ||
|
||||
prop.GetAnnotations().Where(z =>
|
||||
z.Name == "SqlServer:ValueGenerationStrategy" && z.Value.ToString().Contains("IdentityColumn") //sqlserver 自增
|
||||
|| z.Value.ToString().Contains("IdentityColumn") //其他数据库实现未经测试
|
||||
).Any()
|
||||
);
|
||||
//自增
|
||||
freeProp.IsIdentity(
|
||||
prop.ValueGenerated == ValueGenerated.Never ||
|
||||
prop.ValueGenerated == ValueGenerated.OnAdd ||
|
||||
prop.GetAnnotations().Where(z =>
|
||||
z.Name == "SqlServer:ValueGenerationStrategy" && z.Value.ToString().Contains("IdentityColumn") //sqlserver 自增
|
||||
|| z.Value.ToString().Contains("IdentityColumn") //其他数据库实现未经测试
|
||||
).Any()
|
||||
);
|
||||
|
||||
//可空
|
||||
freeProp.IsNullable(prop.AfterSaveBehavior != PropertySaveBehavior.Throw);
|
||||
//可空
|
||||
freeProp.IsNullable(prop.AfterSaveBehavior != PropertySaveBehavior.Throw);
|
||||
|
||||
//类型
|
||||
var relationalColumnType = prop.FindAnnotation("Relational:ColumnType");
|
||||
if (relationalColumnType != null) {
|
||||
//类型
|
||||
var relationalColumnType = prop.FindAnnotation("Relational:ColumnType");
|
||||
if (relationalColumnType != null)
|
||||
{
|
||||
|
||||
var dbType = relationalColumnType.ToString();
|
||||
if (!string.IsNullOrEmpty(dbType)) {
|
||||
var dbType = relationalColumnType.ToString();
|
||||
if (!string.IsNullOrEmpty(dbType))
|
||||
{
|
||||
|
||||
var maxLength = prop.FindAnnotation("MaxLength");
|
||||
if (maxLength != null)
|
||||
dbType += $"({maxLength})";
|
||||
var maxLength = prop.FindAnnotation("MaxLength");
|
||||
if (maxLength != null)
|
||||
dbType += $"({maxLength})";
|
||||
|
||||
freeProp.DbType(dbType);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
freeProp.DbType(dbType);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -1,30 +1,30 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:58143",
|
||||
"sslPort": 44349
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "api/values",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:58143",
|
||||
"sslPort": 44349
|
||||
}
|
||||
},
|
||||
"efcore_to_freesql": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "api/values",
|
||||
"applicationUrl": "https://localhost:5001;http://localhost:5000",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
"profiles": {
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "api/values",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"efcore_to_freesql": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "api/values",
|
||||
"applicationUrl": "https://localhost:5001;http://localhost:5000",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -22,57 +22,59 @@ namespace efcore_to_freesql
|
||||
{
|
||||
Configuration = configuration;
|
||||
|
||||
Fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10")
|
||||
.UseAutoSyncStructure(true)
|
||||
.Build();
|
||||
Fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10")
|
||||
.UseAutoSyncStructure(true)
|
||||
.Build();
|
||||
|
||||
DBContexts.BaseDBContext.Fsql = Fsql;
|
||||
DBContexts.BaseDBContext.Fsql = Fsql;
|
||||
|
||||
var sql11 = Fsql.Select<Topic1>().ToSql();
|
||||
//SELECT a."Id", a."Title", a."CreateTime" FROM "Topic1" a
|
||||
var sql12 = Fsql.Insert<Topic1>().AppendData(new Topic1()).ToSql();
|
||||
//INSERT INTO "Topic1"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0)
|
||||
var sql11 = Fsql.Select<Topic1>().ToSql();
|
||||
//SELECT a."Id", a."Title", a."CreateTime" FROM "Topic1" a
|
||||
var sql12 = Fsql.Insert<Topic1>().AppendData(new Topic1()).ToSql();
|
||||
//INSERT INTO "Topic1"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0)
|
||||
|
||||
var sql21 = Fsql.Select<Topic2>().ToSql();
|
||||
//SELECT a."Id", a."Title", a."CreateTime" FROM "Topic2" a
|
||||
var sql22 = Fsql.Insert<Topic2>().AppendData(new Topic2()).ToSql();
|
||||
//INSERT INTO "Topic2"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0)
|
||||
var sql21 = Fsql.Select<Topic2>().ToSql();
|
||||
//SELECT a."Id", a."Title", a."CreateTime" FROM "Topic2" a
|
||||
var sql22 = Fsql.Insert<Topic2>().AppendData(new Topic2()).ToSql();
|
||||
//INSERT INTO "Topic2"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0)
|
||||
|
||||
using (var db = new Topic1Context()) {
|
||||
db.Topic1s.Add(new Topic1());
|
||||
}
|
||||
using (var db = new Topic2Context()) {
|
||||
db.Topic2s.Add(new Topic2());
|
||||
}
|
||||
using (var db = new Topic1Context())
|
||||
{
|
||||
db.Topic1s.Add(new Topic1());
|
||||
}
|
||||
using (var db = new Topic2Context())
|
||||
{
|
||||
db.Topic2s.Add(new Topic2());
|
||||
}
|
||||
|
||||
var sql13 = Fsql.Select<Topic1>().ToSql();
|
||||
//SELECT a."topic1_id", a."Title", a."CreateTime" FROM "topic1_sss" a
|
||||
var sql14 = Fsql.Insert<Topic1>().AppendData(new Topic1()).ToSql();
|
||||
//INSERT INTO "topic1_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0)
|
||||
var sql13 = Fsql.Select<Topic1>().ToSql();
|
||||
//SELECT a."topic1_id", a."Title", a."CreateTime" FROM "topic1_sss" a
|
||||
var sql14 = Fsql.Insert<Topic1>().AppendData(new Topic1()).ToSql();
|
||||
//INSERT INTO "topic1_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0)
|
||||
|
||||
var sql23 = Fsql.Select<Topic2>().ToSql();
|
||||
//SELECT a."topic2_id", a."Title", a."CreateTime" FROM "topic2_sss" a
|
||||
var sql24 = Fsql.Insert<Topic2>().AppendData(new Topic2()).ToSql();
|
||||
//INSERT INTO "topic2_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0)
|
||||
}
|
||||
var sql23 = Fsql.Select<Topic2>().ToSql();
|
||||
//SELECT a."topic2_id", a."Title", a."CreateTime" FROM "topic2_sss" a
|
||||
var sql24 = Fsql.Insert<Topic2>().AppendData(new Topic2()).ToSql();
|
||||
//INSERT INTO "topic2_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0)
|
||||
}
|
||||
|
||||
public IConfiguration Configuration { get; }
|
||||
public IFreeSql Fsql { get; }
|
||||
public IConfiguration Configuration { get; }
|
||||
public IFreeSql Fsql { get; }
|
||||
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<IFreeSql>(Fsql);
|
||||
services.AddMvc();
|
||||
services.AddSingleton<IFreeSql>(Fsql);
|
||||
services.AddMvc();
|
||||
}
|
||||
|
||||
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
|
||||
{
|
||||
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
|
||||
loggerFactory.AddDebug();
|
||||
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
|
||||
loggerFactory.AddDebug();
|
||||
|
||||
app.UseDeveloperExceptionPage();
|
||||
app.UseMvc();
|
||||
}
|
||||
app.UseDeveloperExceptionPage();
|
||||
app.UseMvc();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Debug",
|
||||
"System": "Information",
|
||||
"Microsoft": "Information"
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Debug",
|
||||
"System": "Information",
|
||||
"Microsoft": "Information"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
|
@ -14,288 +14,317 @@ namespace orm_vs
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
|
||||
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=20")
|
||||
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=20")
|
||||
.UseAutoSyncStructure(false)
|
||||
.UseNoneCommandParameter(true)
|
||||
//.UseConfigEntityFromDbFirst(true)
|
||||
.Build();
|
||||
static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
|
||||
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=20")
|
||||
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=20")
|
||||
.UseAutoSyncStructure(false)
|
||||
.UseNoneCommandParameter(true)
|
||||
//.UseConfigEntityFromDbFirst(true)
|
||||
.Build();
|
||||
|
||||
static SqlSugarClient sugar {
|
||||
get => new SqlSugarClient(new ConnectionConfig() {
|
||||
//不欺负,让连接池100个最小
|
||||
//ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20",
|
||||
//DbType = DbType.SqlServer,
|
||||
ConnectionString = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=20;Max Pool Size=20",
|
||||
DbType = DbType.MySql,
|
||||
IsAutoCloseConnection = true,
|
||||
InitKeyType = InitKeyType.Attribute
|
||||
});
|
||||
}
|
||||
static SqlSugarClient sugar
|
||||
{
|
||||
get => new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
//不欺负,让连接池100个最小
|
||||
//ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20",
|
||||
//DbType = DbType.SqlServer,
|
||||
ConnectionString = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=20;Max Pool Size=20",
|
||||
DbType = DbType.MySql,
|
||||
IsAutoCloseConnection = true,
|
||||
InitKeyType = InitKeyType.Attribute
|
||||
});
|
||||
}
|
||||
|
||||
class SongContext : DbContext {
|
||||
public DbSet<Song> Songs { get; set; }
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
|
||||
//optionsBuilder.UseSqlServer(@"Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=21;Max Pool Size=21");
|
||||
optionsBuilder.UseMySql("Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=21;Max Pool Size=21");
|
||||
}
|
||||
}
|
||||
class SongContext : DbContext
|
||||
{
|
||||
public DbSet<Song> Songs { get; set; }
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
//optionsBuilder.UseSqlServer(@"Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=21;Max Pool Size=21");
|
||||
optionsBuilder.UseMySql("Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=21;Max Pool Size=21");
|
||||
}
|
||||
}
|
||||
|
||||
static void Main(string[] args) {
|
||||
static void Main(string[] args)
|
||||
{
|
||||
|
||||
fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag));
|
||||
//sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag));
|
||||
//sugar创建表失败:SqlSugar.SqlSugarException: Sequence contains no elements
|
||||
fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag));
|
||||
//sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag));
|
||||
//sugar创建表失败:SqlSugar.SqlSugarException: Sequence contains no elements
|
||||
|
||||
sugar.Aop.OnLogExecuted = (s, e) => {
|
||||
Trace.WriteLine(s);
|
||||
};
|
||||
//测试前清空数据
|
||||
fsql.Delete<Song>().Where(a => a.Id > 0).ExecuteAffrows();
|
||||
sugar.Deleteable<Song>().Where(a => a.Id > 0).ExecuteCommand();
|
||||
fsql.Ado.ExecuteNonQuery("delete from efcore_song");
|
||||
sugar.Aop.OnLogExecuted = (s, e) =>
|
||||
{
|
||||
Trace.WriteLine(s);
|
||||
};
|
||||
//测试前清空数据
|
||||
fsql.Delete<Song>().Where(a => a.Id > 0).ExecuteAffrows();
|
||||
sugar.Deleteable<Song>().Where(a => a.Id > 0).ExecuteCommand();
|
||||
fsql.Ado.ExecuteNonQuery("delete from efcore_song");
|
||||
|
||||
var sb = new StringBuilder();
|
||||
Console.WriteLine("插入性能:");
|
||||
Insert(sb, 1000, 1);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Insert(sb, 1000, 10);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
var sb = new StringBuilder();
|
||||
Console.WriteLine("插入性能:");
|
||||
Insert(sb, 1000, 1);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Insert(sb, 1000, 10);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
|
||||
Insert(sb, 1, 1000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Insert(sb, 1, 10000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Insert(sb, 1, 50000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Insert(sb, 1, 100000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Insert(sb, 1, 1000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Insert(sb, 1, 10000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Insert(sb, 1, 50000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Insert(sb, 1, 100000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
|
||||
Console.WriteLine("查询性能:");
|
||||
Select(sb, 1000, 1);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Select(sb, 1000, 10);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Console.WriteLine("查询性能:");
|
||||
Select(sb, 1000, 1);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Select(sb, 1000, 10);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
|
||||
Select(sb, 1, 1000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Select(sb, 1, 10000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Select(sb, 1, 50000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Select(sb, 1, 100000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Select(sb, 1, 1000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Select(sb, 1, 10000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Select(sb, 1, 50000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Select(sb, 1, 100000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
|
||||
Console.WriteLine("更新:");
|
||||
Update(sb, 1000, 1);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Update(sb, 1000, 10);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Console.WriteLine("更新:");
|
||||
Update(sb, 1000, 1);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Update(sb, 1000, 10);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
|
||||
Update(sb, 1, 1000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Update(sb, 1, 10000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Update(sb, 1, 50000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Update(sb, 1, 100000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Update(sb, 1, 1000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Update(sb, 1, 10000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Update(sb, 1, 50000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
Update(sb, 1, 100000);
|
||||
Console.Write(sb.ToString());
|
||||
sb.Clear();
|
||||
|
||||
Console.WriteLine("测试结束,按任意键退出...");
|
||||
Console.ReadKey();
|
||||
}
|
||||
Console.WriteLine("测试结束,按任意键退出...");
|
||||
Console.ReadKey();
|
||||
}
|
||||
|
||||
static void Select(StringBuilder sb, int forTime, int size) {
|
||||
Stopwatch sw = new Stopwatch();
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++)
|
||||
fsql.Select<Song>().Limit(size).ToList();
|
||||
sw.Stop();
|
||||
sb.AppendLine($"FreeSql Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
|
||||
static void Select(StringBuilder sb, int forTime, int size)
|
||||
{
|
||||
Stopwatch sw = new Stopwatch();
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++)
|
||||
fsql.Select<Song>().Limit(size).ToList();
|
||||
sw.Stop();
|
||||
sb.AppendLine($"FreeSql Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
|
||||
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++)
|
||||
sugar.Queryable<Song>().Take(size).ToList();
|
||||
sw.Stop();
|
||||
sb.AppendLine($"SqlSugar Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++)
|
||||
sugar.Queryable<Song>().Take(size).ToList();
|
||||
sw.Stop();
|
||||
sb.AppendLine($"SqlSugar Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
|
||||
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++) {
|
||||
using (var db = new SongContext()) {
|
||||
db.Songs.Take(size).AsNoTracking().ToList();
|
||||
}
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"EFCore Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
|
||||
}
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++)
|
||||
{
|
||||
using (var db = new SongContext())
|
||||
{
|
||||
db.Songs.Take(size).AsNoTracking().ToList();
|
||||
}
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"EFCore Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
|
||||
}
|
||||
|
||||
static void Insert(StringBuilder sb, int forTime, int size) {
|
||||
var songs = Enumerable.Range(0, size).Select(a => new Song {
|
||||
Create_time = DateTime.Now,
|
||||
Is_deleted = false,
|
||||
Title = $"Insert_{a}",
|
||||
Url = $"Url_{a}"
|
||||
});
|
||||
static void Insert(StringBuilder sb, int forTime, int size)
|
||||
{
|
||||
var songs = Enumerable.Range(0, size).Select(a => new Song
|
||||
{
|
||||
Create_time = DateTime.Now,
|
||||
Is_deleted = false,
|
||||
Title = $"Insert_{a}",
|
||||
Url = $"Url_{a}"
|
||||
});
|
||||
|
||||
//预热
|
||||
fsql.Insert(songs.First()).ExecuteAffrows();
|
||||
sugar.Insertable(songs.First()).ExecuteCommand();
|
||||
using (var db = new SongContext()) {
|
||||
//db.Configuration.AutoDetectChangesEnabled = false;
|
||||
db.Songs.AddRange(songs.First());
|
||||
db.SaveChanges();
|
||||
}
|
||||
Stopwatch sw = new Stopwatch();
|
||||
//预热
|
||||
fsql.Insert(songs.First()).ExecuteAffrows();
|
||||
sugar.Insertable(songs.First()).ExecuteCommand();
|
||||
using (var db = new SongContext())
|
||||
{
|
||||
//db.Configuration.AutoDetectChangesEnabled = false;
|
||||
db.Songs.AddRange(songs.First());
|
||||
db.SaveChanges();
|
||||
}
|
||||
Stopwatch sw = new Stopwatch();
|
||||
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++) {
|
||||
fsql.Insert(songs).ExecuteAffrows();
|
||||
//using (var db = new FreeSongContext()) {
|
||||
// //db.Configuration.AutoDetectChangesEnabled = false;
|
||||
// db.Songs.AddRange(songs.ToArray());
|
||||
// db.SaveChanges();
|
||||
//}
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"FreeSql Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++)
|
||||
{
|
||||
fsql.Insert(songs).ExecuteAffrows();
|
||||
//using (var db = new FreeSongContext()) {
|
||||
// //db.Configuration.AutoDetectChangesEnabled = false;
|
||||
// db.Songs.AddRange(songs.ToArray());
|
||||
// db.SaveChanges();
|
||||
//}
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"FreeSql Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
|
||||
|
||||
sw.Restart();
|
||||
Exception sugarEx = null;
|
||||
try {
|
||||
for (var a = 0; a < forTime; a++)
|
||||
sugar.Insertable(songs.ToArray()).ExecuteCommand();
|
||||
} catch (Exception ex) {
|
||||
sugarEx = ex;
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"SqlSugar Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));
|
||||
sw.Restart();
|
||||
Exception sugarEx = null;
|
||||
try
|
||||
{
|
||||
for (var a = 0; a < forTime; a++)
|
||||
sugar.Insertable(songs.ToArray()).ExecuteCommand();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
sugarEx = ex;
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"SqlSugar Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));
|
||||
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++) {
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++)
|
||||
{
|
||||
|
||||
using (var db = new SongContext()) {
|
||||
//db.Configuration.AutoDetectChangesEnabled = false;
|
||||
db.Songs.AddRange(songs.ToArray());
|
||||
db.SaveChanges();
|
||||
}
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"EFCore Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
|
||||
}
|
||||
using (var db = new SongContext())
|
||||
{
|
||||
//db.Configuration.AutoDetectChangesEnabled = false;
|
||||
db.Songs.AddRange(songs.ToArray());
|
||||
db.SaveChanges();
|
||||
}
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"EFCore Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
|
||||
}
|
||||
|
||||
static void Update(StringBuilder sb, int forTime, int size) {
|
||||
Stopwatch sw = new Stopwatch();
|
||||
static void Update(StringBuilder sb, int forTime, int size)
|
||||
{
|
||||
Stopwatch sw = new Stopwatch();
|
||||
|
||||
var songs = fsql.Select<Song>().Limit(size).ToList();
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++) {
|
||||
fsql.Update<Song>().SetSource(songs).ExecuteAffrows();
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"FreeSql Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
|
||||
var songs = fsql.Select<Song>().Limit(size).ToList();
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++)
|
||||
{
|
||||
fsql.Update<Song>().SetSource(songs).ExecuteAffrows();
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"FreeSql Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
|
||||
|
||||
songs = sugar.Queryable<Song>().Take(size).ToList();
|
||||
sw.Restart();
|
||||
Exception sugarEx = null;
|
||||
try {
|
||||
for (var a = 0; a < forTime; a++)
|
||||
sugar.Updateable(songs).ExecuteCommand();
|
||||
} catch (Exception ex) {
|
||||
sugarEx = ex;
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"SqlSugar Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));
|
||||
songs = sugar.Queryable<Song>().Take(size).ToList();
|
||||
sw.Restart();
|
||||
Exception sugarEx = null;
|
||||
try
|
||||
{
|
||||
for (var a = 0; a < forTime; a++)
|
||||
sugar.Updateable(songs).ExecuteCommand();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
sugarEx = ex;
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"SqlSugar Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));
|
||||
|
||||
using (var db = new SongContext()) {
|
||||
songs = db.Songs.Take(size).AsNoTracking().ToList();
|
||||
}
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++) {
|
||||
using (var db = new SongContext())
|
||||
{
|
||||
songs = db.Songs.Take(size).AsNoTracking().ToList();
|
||||
}
|
||||
sw.Restart();
|
||||
for (var a = 0; a < forTime; a++)
|
||||
{
|
||||
|
||||
using (var db = new SongContext()) {
|
||||
//db.Configuration.AutoDetectChangesEnabled = false;
|
||||
db.Songs.UpdateRange(songs.ToArray());
|
||||
db.SaveChanges();
|
||||
}
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"EFCore Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
|
||||
}
|
||||
}
|
||||
using (var db = new SongContext())
|
||||
{
|
||||
//db.Configuration.AutoDetectChangesEnabled = false;
|
||||
db.Songs.UpdateRange(songs.ToArray());
|
||||
db.SaveChanges();
|
||||
}
|
||||
}
|
||||
sw.Stop();
|
||||
sb.AppendLine($"EFCore Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
|
||||
}
|
||||
}
|
||||
|
||||
[FreeSql.DataAnnotations.Table(Name = "freesql_song")]
|
||||
[SugarTable("sugar_song")]
|
||||
[Table("efcore_song")]
|
||||
public class Song {
|
||||
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
|
||||
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
[Key]
|
||||
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||
public int Id { get; set; }
|
||||
public DateTime? Create_time { get; set; }
|
||||
public bool? Is_deleted { get; set; }
|
||||
public string Title { get; set; }
|
||||
public string Url { get; set; }
|
||||
[FreeSql.DataAnnotations.Table(Name = "freesql_song")]
|
||||
[SugarTable("sugar_song")]
|
||||
[Table("efcore_song")]
|
||||
public class Song
|
||||
{
|
||||
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
|
||||
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
[Key]
|
||||
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||
public int Id { get; set; }
|
||||
public DateTime? Create_time { get; set; }
|
||||
public bool? Is_deleted { get; set; }
|
||||
public string Title { get; set; }
|
||||
public string Url { get; set; }
|
||||
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual ICollection<Tag> Tags { get; set; }
|
||||
}
|
||||
[FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")]
|
||||
[SugarTable("sugar_song_tag")]
|
||||
[Table("efcore_song_tag")]
|
||||
public class Song_tag {
|
||||
public int Song_id { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual Song Song { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual ICollection<Tag> Tags { get; set; }
|
||||
}
|
||||
[FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")]
|
||||
[SugarTable("sugar_song_tag")]
|
||||
[Table("efcore_song_tag")]
|
||||
public class Song_tag
|
||||
{
|
||||
public int Song_id { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual Song Song { get; set; }
|
||||
|
||||
public int Tag_id { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual Tag Tag { get; set; }
|
||||
}
|
||||
[FreeSql.DataAnnotations.Table(Name = "freesql_tag")]
|
||||
[SugarTable("sugar_tag")]
|
||||
[Table("efcore_tag")]
|
||||
public class Tag {
|
||||
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
|
||||
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
[Key]
|
||||
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||
public int Id { get; set; }
|
||||
public int? Parent_id { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual Tag Parent { get; set; }
|
||||
public int Tag_id { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual Tag Tag { get; set; }
|
||||
}
|
||||
[FreeSql.DataAnnotations.Table(Name = "freesql_tag")]
|
||||
[SugarTable("sugar_tag")]
|
||||
[Table("efcore_tag")]
|
||||
public class Tag
|
||||
{
|
||||
[FreeSql.DataAnnotations.Column(IsIdentity = true)]
|
||||
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
[Key]
|
||||
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||
public int Id { get; set; }
|
||||
public int? Parent_id { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual Tag Parent { get; set; }
|
||||
|
||||
public decimal? Ddd { get; set; }
|
||||
public string Name { get; set; }
|
||||
public decimal? Ddd { get; set; }
|
||||
public string Name { get; set; }
|
||||
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual ICollection<Song> Songs { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual ICollection<Tag> Tags { get; set; }
|
||||
}
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual ICollection<Song> Songs { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
[NotMapped]
|
||||
public virtual ICollection<Tag> Tags { get; set; }
|
||||
}
|
||||
}
|
||||
|
@ -6,93 +6,107 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace restful.Controllers {
|
||||
namespace restful.Controllers
|
||||
{
|
||||
|
||||
public class SongRepository : GuidRepository<Song> {
|
||||
public SongRepository(IFreeSql fsql) : base(fsql) {
|
||||
}
|
||||
}
|
||||
public class SongRepository : GuidRepository<Song>
|
||||
{
|
||||
public SongRepository(IFreeSql fsql) : base(fsql)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
[Route("restapi/[controller]")]
|
||||
public class SongsController : Controller {
|
||||
[Route("restapi/[controller]")]
|
||||
public class SongsController : Controller
|
||||
{
|
||||
|
||||
BaseRepository<Song, int> _songRepository;
|
||||
BaseRepository<Song, int> _songRepository;
|
||||
|
||||
public class xxxx {
|
||||
public int Id { get; set; }
|
||||
public class xxxx
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
}
|
||||
public bool IsDeleted { get; set; }
|
||||
}
|
||||
|
||||
|
||||
|
||||
public SongsController(IFreeSql fsql,
|
||||
GuidRepository<Song> repos1,
|
||||
GuidRepository<xxxx> repos2,
|
||||
|
||||
DefaultRepository<Song, int> repos11,
|
||||
DefaultRepository<xxxx, int> repos21,
|
||||
public SongsController(IFreeSql fsql,
|
||||
GuidRepository<Song> repos1,
|
||||
GuidRepository<xxxx> repos2,
|
||||
|
||||
BaseRepository<Song> repos3, BaseRepository<Song, int> repos4,
|
||||
IBasicRepository<Song> repos31, IBasicRepository<Song, int> repos41,
|
||||
IReadOnlyRepository<Song> repos311, IReadOnlyRepository<Song, int> repos411,
|
||||
DefaultRepository<Song, int> repos11,
|
||||
DefaultRepository<xxxx, int> repos21,
|
||||
|
||||
SongRepository reposSong
|
||||
) {
|
||||
_songRepository = repos4;
|
||||
BaseRepository<Song> repos3, BaseRepository<Song, int> repos4,
|
||||
IBasicRepository<Song> repos31, IBasicRepository<Song, int> repos41,
|
||||
IReadOnlyRepository<Song> repos311, IReadOnlyRepository<Song, int> repos411,
|
||||
|
||||
//test code
|
||||
var curd1 = fsql.GetRepository<Song, int>();
|
||||
var curd2 = fsql.GetRepository<Song, string>();
|
||||
var curd3 = fsql.GetRepository<Song, Guid>();
|
||||
var curd4 = fsql.GetGuidRepository<Song>();
|
||||
SongRepository reposSong
|
||||
)
|
||||
{
|
||||
_songRepository = repos4;
|
||||
|
||||
Console.WriteLine(repos1.Select.ToSql());
|
||||
Console.WriteLine(reposSong.Select.ToSql());
|
||||
//test code
|
||||
var curd1 = fsql.GetRepository<Song, int>();
|
||||
var curd2 = fsql.GetRepository<Song, string>();
|
||||
var curd3 = fsql.GetRepository<Song, Guid>();
|
||||
var curd4 = fsql.GetGuidRepository<Song>();
|
||||
|
||||
Console.WriteLine(repos2.Select.ToSql());
|
||||
Console.WriteLine(repos21.Select.ToSql());
|
||||
Console.WriteLine(repos1.Select.ToSql());
|
||||
Console.WriteLine(reposSong.Select.ToSql());
|
||||
|
||||
using (reposSong.DataFilter.DisableAll()) {
|
||||
Console.WriteLine(reposSong.Select.ToSql());
|
||||
}
|
||||
}
|
||||
Console.WriteLine(repos2.Select.ToSql());
|
||||
Console.WriteLine(repos21.Select.ToSql());
|
||||
|
||||
[HttpGet]
|
||||
public Task<List<Song>> GetItems([FromQuery] string key, [FromQuery] int page = 1, [FromQuery] int limit = 20) {
|
||||
return _songRepository.Select.WhereIf(!string.IsNullOrEmpty(key), a => a.Title.Contains(key)).Page(page, limit).ToListAsync();
|
||||
}
|
||||
using (reposSong.DataFilter.DisableAll())
|
||||
{
|
||||
Console.WriteLine(reposSong.Select.ToSql());
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("{id}")]
|
||||
public Task<Song> GetItem([FromRoute] int id) {
|
||||
return _songRepository.FindAsync(id);
|
||||
}
|
||||
[HttpGet]
|
||||
public Task<List<Song>> GetItems([FromQuery] string key, [FromQuery] int page = 1, [FromQuery] int limit = 20)
|
||||
{
|
||||
return _songRepository.Select.WhereIf(!string.IsNullOrEmpty(key), a => a.Title.Contains(key)).Page(page, limit).ToListAsync();
|
||||
}
|
||||
|
||||
public class ModelSong {
|
||||
public string title { get; set; }
|
||||
}
|
||||
[HttpGet("{id}")]
|
||||
public Task<Song> GetItem([FromRoute] int id)
|
||||
{
|
||||
return _songRepository.FindAsync(id);
|
||||
}
|
||||
|
||||
[HttpPost, ProducesResponseType(201)]
|
||||
public Task<Song> Create([FromBody] ModelSong model) {
|
||||
return _songRepository.InsertAsync(new Song { Title = model.title });
|
||||
}
|
||||
public class ModelSong
|
||||
{
|
||||
public string title { get; set; }
|
||||
}
|
||||
|
||||
[HttpPut("{id}")]
|
||||
public Task Update([FromRoute] int id, [FromBody] ModelSong model) {
|
||||
return _songRepository.UpdateAsync(new Song { Id = id, Title = model.title });
|
||||
}
|
||||
[HttpPost, ProducesResponseType(201)]
|
||||
public Task<Song> Create([FromBody] ModelSong model)
|
||||
{
|
||||
return _songRepository.InsertAsync(new Song { Title = model.title });
|
||||
}
|
||||
|
||||
[HttpPatch("{id}")]
|
||||
async public Task<Song> UpdateDiy([FromRoute] int id, [FromForm] string title) {
|
||||
var up = _songRepository.UpdateDiy.Where(a => a.Id == id);
|
||||
if (!string.IsNullOrEmpty(title)) up.Set(a => a.Title, title);
|
||||
var ret = await up.ExecuteUpdatedAsync();
|
||||
return ret.FirstOrDefault();
|
||||
}
|
||||
[HttpPut("{id}")]
|
||||
public Task Update([FromRoute] int id, [FromBody] ModelSong model)
|
||||
{
|
||||
return _songRepository.UpdateAsync(new Song { Id = id, Title = model.title });
|
||||
}
|
||||
|
||||
[HttpDelete("{id}"), ProducesResponseType(204)]
|
||||
public Task Delete([FromRoute] int id) {
|
||||
return _songRepository.DeleteAsync(a => a.Id == id);
|
||||
}
|
||||
}
|
||||
[HttpPatch("{id}")]
|
||||
async public Task<Song> UpdateDiy([FromRoute] int id, [FromForm] string title)
|
||||
{
|
||||
var up = _songRepository.UpdateDiy.Where(a => a.Id == id);
|
||||
if (!string.IsNullOrEmpty(title)) up.Set(a => a.Title, title);
|
||||
var ret = await up.ExecuteUpdatedAsync();
|
||||
return ret.FirstOrDefault();
|
||||
}
|
||||
|
||||
[HttpDelete("{id}"), ProducesResponseType(204)]
|
||||
public Task Delete([FromRoute] int id)
|
||||
{
|
||||
return _songRepository.DeleteAsync(a => a.Id == id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,11 +1,13 @@
|
||||
using FreeSql.DataAnnotations;
|
||||
using repository_01;
|
||||
|
||||
namespace restful.Entitys {
|
||||
public class Song {
|
||||
namespace restful.Entitys
|
||||
{
|
||||
public class Song
|
||||
{
|
||||
|
||||
[Column(IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public string Title { get; set; }
|
||||
}
|
||||
[Column(IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public string Title { get; set; }
|
||||
}
|
||||
}
|
||||
|
@ -1,27 +1,27 @@
|
||||
{
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:52751/",
|
||||
"sslPort": 0
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:52751/",
|
||||
"sslPort": 0
|
||||
}
|
||||
},
|
||||
"repository_01": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"applicationUrl": "http://localhost:52752/"
|
||||
"profiles": {
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"repository_01": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"applicationUrl": "http://localhost:52752/"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -13,86 +13,98 @@ using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace repository_01 {
|
||||
namespace repository_01
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 用户密码信息
|
||||
/// </summary>
|
||||
public class Sys1UserLogOn {
|
||||
[Column(IsPrimary = true, Name = "Id")]
|
||||
public Guid UserLogOnId { get; set; }
|
||||
public virtual Sys1User User { get; set; }
|
||||
}
|
||||
public class Sys1User {
|
||||
[Column(IsPrimary = true, Name = "Id")]
|
||||
public Guid UserId { get; set; }
|
||||
public virtual Sys1UserLogOn UserLogOn { get; set; }
|
||||
}
|
||||
|
||||
public class Startup {
|
||||
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) {
|
||||
Configuration = configuration;
|
||||
/// <summary>
|
||||
/// 用户密码信息
|
||||
/// </summary>
|
||||
public class Sys1UserLogOn
|
||||
{
|
||||
[Column(IsPrimary = true, Name = "Id")]
|
||||
public Guid UserLogOnId { get; set; }
|
||||
public virtual Sys1User User { get; set; }
|
||||
}
|
||||
public class Sys1User
|
||||
{
|
||||
[Column(IsPrimary = true, Name = "Id")]
|
||||
public Guid UserId { get; set; }
|
||||
public virtual Sys1UserLogOn UserLogOn { get; set; }
|
||||
}
|
||||
|
||||
Fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10")
|
||||
.UseAutoSyncStructure(true)
|
||||
.UseLazyLoading(true)
|
||||
public class Startup
|
||||
{
|
||||
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
|
||||
{
|
||||
Configuration = configuration;
|
||||
|
||||
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
|
||||
.Build();
|
||||
Fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10")
|
||||
.UseAutoSyncStructure(true)
|
||||
.UseLazyLoading(true)
|
||||
|
||||
var sysu = new Sys1User { };
|
||||
Fsql.Insert<Sys1User>().AppendData(sysu).ExecuteAffrows();
|
||||
Fsql.Insert<Sys1UserLogOn>().AppendData(new Sys1UserLogOn { UserLogOnId = sysu.UserId }).ExecuteAffrows();
|
||||
var a = Fsql.Select<Sys1UserLogOn>().ToList();
|
||||
var b = Fsql.Select<Sys1UserLogOn>().Any();
|
||||
}
|
||||
.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
|
||||
.Build();
|
||||
|
||||
public IConfiguration Configuration { get; }
|
||||
public static IFreeSql Fsql { get; private set; }
|
||||
var sysu = new Sys1User { };
|
||||
Fsql.Insert<Sys1User>().AppendData(sysu).ExecuteAffrows();
|
||||
Fsql.Insert<Sys1UserLogOn>().AppendData(new Sys1UserLogOn { UserLogOnId = sysu.UserId }).ExecuteAffrows();
|
||||
var a = Fsql.Select<Sys1UserLogOn>().ToList();
|
||||
var b = Fsql.Select<Sys1UserLogOn>().Any();
|
||||
}
|
||||
|
||||
public void ConfigureServices(IServiceCollection services) {
|
||||
public IConfiguration Configuration { get; }
|
||||
public static IFreeSql Fsql { get; private set; }
|
||||
|
||||
//services.AddTransient(s => s.)
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
|
||||
services.AddMvc();
|
||||
services.AddSwaggerGen(options => {
|
||||
options.SwaggerDoc("v1", new Info {
|
||||
Version = "v1",
|
||||
Title = "FreeSql.RESTful API"
|
||||
});
|
||||
//options.IncludeXmlComments(xmlPath);
|
||||
});
|
||||
//services.AddTransient(s => s.)
|
||||
|
||||
services.AddSingleton<IFreeSql>(Fsql);
|
||||
services.AddMvc();
|
||||
services.AddSwaggerGen(options =>
|
||||
{
|
||||
options.SwaggerDoc("v1", new Info
|
||||
{
|
||||
Version = "v1",
|
||||
Title = "FreeSql.RESTful API"
|
||||
});
|
||||
//options.IncludeXmlComments(xmlPath);
|
||||
});
|
||||
|
||||
services.AddFreeRepository(filter => {
|
||||
filter
|
||||
//.Apply<Song>("test", a => a.Title == DateTime.Now.ToString() + System.Threading.Thread.CurrentThread.ManagedThreadId)
|
||||
.Apply<ISoftDelete>("softdelete", a => a.IsDeleted == false);
|
||||
}, this.GetType().Assembly);
|
||||
}
|
||||
services.AddSingleton<IFreeSql>(Fsql);
|
||||
|
||||
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
|
||||
Console.InputEncoding = Encoding.GetEncoding("GB2312");
|
||||
services.AddFreeRepository(filter =>
|
||||
{
|
||||
filter
|
||||
//.Apply<Song>("test", a => a.Title == DateTime.Now.ToString() + System.Threading.Thread.CurrentThread.ManagedThreadId)
|
||||
.Apply<ISoftDelete>("softdelete", a => a.IsDeleted == false);
|
||||
}, this.GetType().Assembly);
|
||||
}
|
||||
|
||||
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
|
||||
loggerFactory.AddDebug();
|
||||
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
|
||||
{
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
|
||||
Console.InputEncoding = Encoding.GetEncoding("GB2312");
|
||||
|
||||
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
|
||||
app.UseDeveloperExceptionPage();
|
||||
app.UseMvc();
|
||||
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
|
||||
loggerFactory.AddDebug();
|
||||
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(c => {
|
||||
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
|
||||
});
|
||||
}
|
||||
}
|
||||
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
|
||||
app.UseDeveloperExceptionPage();
|
||||
app.UseMvc();
|
||||
|
||||
public interface ISoftDelete {
|
||||
bool IsDeleted { get; set; }
|
||||
}
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(c =>
|
||||
{
|
||||
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public interface ISoftDelete
|
||||
{
|
||||
bool IsDeleted { get; set; }
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Debug",
|
||||
"System": "Warning",
|
||||
"Microsoft": "Warning"
|
||||
}
|
||||
}
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Debug",
|
||||
"System": "Warning",
|
||||
"Microsoft": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
|
@ -4,56 +4,66 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace restful.Controllers {
|
||||
namespace restful.Controllers
|
||||
{
|
||||
|
||||
|
||||
[Route("restapi/[controller]")]
|
||||
public class SongsController : Controller {
|
||||
[Route("restapi/[controller]")]
|
||||
public class SongsController : Controller
|
||||
{
|
||||
|
||||
IFreeSql _fsql;
|
||||
IFreeSql _fsql;
|
||||
|
||||
public SongsController(IFreeSql fsql) {
|
||||
_fsql = fsql;
|
||||
}
|
||||
public SongsController(IFreeSql fsql)
|
||||
{
|
||||
_fsql = fsql;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public Task<List<Song>> GetItems([FromQuery] string key, [FromQuery] int page = 1, [FromQuery] int limit = 20) {
|
||||
return _fsql.Select<Song>().WhereIf(!string.IsNullOrEmpty(key), a => a.Title.Contains(key)).Page(page, limit).ToListAsync();
|
||||
}
|
||||
[HttpGet]
|
||||
public Task<List<Song>> GetItems([FromQuery] string key, [FromQuery] int page = 1, [FromQuery] int limit = 20)
|
||||
{
|
||||
return _fsql.Select<Song>().WhereIf(!string.IsNullOrEmpty(key), a => a.Title.Contains(key)).Page(page, limit).ToListAsync();
|
||||
}
|
||||
|
||||
[HttpGet("{id}")]
|
||||
public Task<Song> GetItem([FromRoute] int id) {
|
||||
return _fsql.Select<Song>().Where(a => a.Id == id).ToOneAsync();
|
||||
}
|
||||
[HttpGet("{id}")]
|
||||
public Task<Song> GetItem([FromRoute] int id)
|
||||
{
|
||||
return _fsql.Select<Song>().Where(a => a.Id == id).ToOneAsync();
|
||||
}
|
||||
|
||||
public class ModelSong {
|
||||
public string title { get; set; }
|
||||
}
|
||||
public class ModelSong
|
||||
{
|
||||
public string title { get; set; }
|
||||
}
|
||||
|
||||
[HttpPost, ProducesResponseType(201)]
|
||||
async public Task<Song> Create([FromBody] ModelSong model) {
|
||||
var ret = await _fsql.Insert<Song>().AppendData(new Song { Title = model.title }).ExecuteInsertedAsync();
|
||||
return ret.FirstOrDefault();
|
||||
}
|
||||
[HttpPost, ProducesResponseType(201)]
|
||||
async public Task<Song> Create([FromBody] ModelSong model)
|
||||
{
|
||||
var ret = await _fsql.Insert<Song>().AppendData(new Song { Title = model.title }).ExecuteInsertedAsync();
|
||||
return ret.FirstOrDefault();
|
||||
}
|
||||
|
||||
[HttpPut("{id}")]
|
||||
async public Task<Song> Update([FromRoute] int id, [FromBody] ModelSong model) {
|
||||
var ret = await _fsql.Update<Song>().SetSource(new Song { Id = id, Title = model.title }).ExecuteUpdatedAsync();
|
||||
return ret.FirstOrDefault();
|
||||
}
|
||||
[HttpPut("{id}")]
|
||||
async public Task<Song> Update([FromRoute] int id, [FromBody] ModelSong model)
|
||||
{
|
||||
var ret = await _fsql.Update<Song>().SetSource(new Song { Id = id, Title = model.title }).ExecuteUpdatedAsync();
|
||||
return ret.FirstOrDefault();
|
||||
}
|
||||
|
||||
[HttpPatch("{id}")]
|
||||
async public Task<Song> UpdateDiy([FromRoute] int id, [FromForm] string title) {
|
||||
var up = _fsql.Update<Song>().Where(a => a.Id == id);
|
||||
if (!string.IsNullOrEmpty(title)) up.Set(a => a.Title, title);
|
||||
var ret = await up.ExecuteUpdatedAsync();
|
||||
return ret.FirstOrDefault();
|
||||
}
|
||||
[HttpPatch("{id}")]
|
||||
async public Task<Song> UpdateDiy([FromRoute] int id, [FromForm] string title)
|
||||
{
|
||||
var up = _fsql.Update<Song>().Where(a => a.Id == id);
|
||||
if (!string.IsNullOrEmpty(title)) up.Set(a => a.Title, title);
|
||||
var ret = await up.ExecuteUpdatedAsync();
|
||||
return ret.FirstOrDefault();
|
||||
}
|
||||
|
||||
[HttpDelete("{id}"), ProducesResponseType(204)]
|
||||
async public Task<Song> Delete([FromRoute] int id) {
|
||||
var ret = await _fsql.Delete<Song>().Where(a => a.Id == id).ExecuteDeletedAsync();
|
||||
return ret.FirstOrDefault();
|
||||
}
|
||||
}
|
||||
[HttpDelete("{id}"), ProducesResponseType(204)]
|
||||
async public Task<Song> Delete([FromRoute] int id)
|
||||
{
|
||||
var ret = await _fsql.Delete<Song>().Where(a => a.Id == id).ExecuteDeletedAsync();
|
||||
return ret.FirstOrDefault();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,12 @@
|
||||
using FreeSql.DataAnnotations;
|
||||
|
||||
namespace restful.Entitys {
|
||||
public class Song {
|
||||
namespace restful.Entitys
|
||||
{
|
||||
public class Song
|
||||
{
|
||||
|
||||
[Column(IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public string Title { get; set; }
|
||||
}
|
||||
[Column(IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public string Title { get; set; }
|
||||
}
|
||||
}
|
||||
|
@ -1,27 +1,27 @@
|
||||
{
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:49778/",
|
||||
"sslPort": 0
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:49778/",
|
||||
"sslPort": 0
|
||||
}
|
||||
},
|
||||
"FreeSql.RESTful.Demo": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"applicationUrl": "http://localhost:49779/"
|
||||
"profiles": {
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"FreeSql.RESTful.Demo": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"applicationUrl": "http://localhost:49779/"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -7,61 +7,71 @@ using Swashbuckle.AspNetCore.Swagger;
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace restful {
|
||||
public class Startup {
|
||||
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) {
|
||||
Configuration = configuration;
|
||||
namespace restful
|
||||
{
|
||||
public class Startup
|
||||
{
|
||||
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
|
||||
{
|
||||
Configuration = configuration;
|
||||
|
||||
Fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10")
|
||||
.UseAutoSyncStructure(true)
|
||||
.Build();
|
||||
Fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10")
|
||||
.UseAutoSyncStructure(true)
|
||||
.Build();
|
||||
|
||||
Fsql.Aop.CurdAfter = (s, e) => {
|
||||
if (e.ElapsedMilliseconds > 200) {
|
||||
//记录日志
|
||||
//发送短信给负责人
|
||||
}
|
||||
};
|
||||
Fsql.Aop.CurdAfter = (s, e) =>
|
||||
{
|
||||
if (e.ElapsedMilliseconds > 200)
|
||||
{
|
||||
//记录日志
|
||||
//发送短信给负责人
|
||||
}
|
||||
};
|
||||
|
||||
//Fsql.Aop.Where = (s, e) => {
|
||||
// if (e.Parameters[0]?.ToString() == "1")
|
||||
// e.IsCancel = true;
|
||||
//};
|
||||
}
|
||||
//Fsql.Aop.Where = (s, e) => {
|
||||
// if (e.Parameters[0]?.ToString() == "1")
|
||||
// e.IsCancel = true;
|
||||
//};
|
||||
}
|
||||
|
||||
public IConfiguration Configuration { get; }
|
||||
public IFreeSql Fsql { get; }
|
||||
public IConfiguration Configuration { get; }
|
||||
public IFreeSql Fsql { get; }
|
||||
|
||||
public void ConfigureServices(IServiceCollection services) {
|
||||
services.AddSingleton<IFreeSql>(Fsql);
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<IFreeSql>(Fsql);
|
||||
|
||||
services.AddMvc();
|
||||
services.AddSwaggerGen(options => {
|
||||
options.SwaggerDoc("v1", new Info {
|
||||
Version = "v1",
|
||||
Title = "FreeSql.RESTful API"
|
||||
});
|
||||
//options.IncludeXmlComments(xmlPath);
|
||||
});
|
||||
}
|
||||
services.AddMvc();
|
||||
services.AddSwaggerGen(options =>
|
||||
{
|
||||
options.SwaggerDoc("v1", new Info
|
||||
{
|
||||
Version = "v1",
|
||||
Title = "FreeSql.RESTful API"
|
||||
});
|
||||
//options.IncludeXmlComments(xmlPath);
|
||||
});
|
||||
}
|
||||
|
||||
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
|
||||
Console.InputEncoding = Encoding.GetEncoding("GB2312");
|
||||
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
|
||||
{
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
|
||||
Console.InputEncoding = Encoding.GetEncoding("GB2312");
|
||||
|
||||
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
|
||||
loggerFactory.AddDebug();
|
||||
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
|
||||
loggerFactory.AddDebug();
|
||||
|
||||
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
|
||||
app.UseDeveloperExceptionPage();
|
||||
app.UseMvc();
|
||||
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
|
||||
app.UseDeveloperExceptionPage();
|
||||
app.UseMvc();
|
||||
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(c => {
|
||||
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
|
||||
});
|
||||
}
|
||||
}
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(c =>
|
||||
{
|
||||
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Debug",
|
||||
"System": "Information",
|
||||
"Microsoft": "Information"
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Debug",
|
||||
"System": "Information",
|
||||
"Microsoft": "Information"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
|
Reference in New Issue
Block a user