FreeSql.DbContext 實現相似 EFCore 使用方法,跟蹤對象狀態,最終經過 SaveChanges 方法提交事務。git
目前是第二個第一版,已實現狀態跟蹤保存(導航屬性的跟蹤暫時不支持)。github
另外還缺乏 rowversion 行鎖機制,這個現實好就能夠在項目中使用了。sql
dotnet add package FreeSql.DbContextmvc
一、在 OnConfiguring 方法上配置與 IFreeSql 關聯。異步
說明:DbContext、DbSet 是 FreeSql 命名空間下的類。ide
public class SongContext : DbContext { public DbSet<Song> Songs { get; set; } public DbSet<Song> Tags { get; set; } 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 virtual ICollection<Tag> Tags { 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 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 virtual ICollection<Song> Songs { get; set; } public virtual ICollection<Tag> Tags { get; set; } }
使用的時候與 EFCore 相似:性能
long id = 0; using (var ctx = new SongContext()) { var song = new Song { }; await ctx.Songs.AddAsync(song); id = song.Id; var adds = Enumerable.Range(0, 100) .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" }) .ToList(); await ctx.Songs.AddRangeAsync(adds); for (var a = 0; a < adds.Count; a++) adds[a].Title = "dkdkdkdk" + a; ctx.Songs.UpdateRange(adds); ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList()); //ctx.Songs.Update(adds.First()); adds.Last().Url = "skldfjlksdjglkjjcccc"; ctx.Songs.Update(adds.Last()); //throw new Exception("回滾"); await ctx.SaveChangesAsync(); }
二、注入方式使用測試
public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IFreeSql>(Fsql); services.AddFreeDbContext<SongContext>(options => options.UseFreeSql(Fsql)); }
在 mvc 中獲取:ui
IFreeSql _orm; public ValuesController(SongContext songContext) { }
OnConfiguring > AddFreeDbContexturl
DbContext SaveChanges 性能測試結果挺可觀,待完善之日再發一篇專門的性能測試文章。
FreeSql 正在以快速演進的方式在更新,請求獻上寶貴的一星,謝謝!