-
Notifications
You must be signed in to change notification settings - Fork 858
DbContext
28810 edited this page Mar 21, 2019
·
30 revisions
FreeSql.DbContext 实现类似 EFCore 使用方法,跟踪对象状态,最终通过 SaveChanges 方法提交事务。
目前是第二个初版,已实现状态跟踪保存(导航属性的跟踪暂时不支持)。
另外还缺少 rowversion 行锁机制,这个现实好就可以在项目中使用了。
dotnet add package FreeSql.DbContext
1、在 OnConfiguring 方法上配置与 IFreeSql 关联
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();
}
2、注入方式使用
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IFreeSql>(Fsql);
services.AddFreeDbContext<SongContext>(options => options.UseFreeSql(Fsql));
}
在 mvc 中获取:
IFreeSql _orm;
public ValuesController(SongContext songContext) {
}
OnConfiguring > AddFreeDbContext
- DbContext 操作的数据在最后 SaveChanges 时才批量保存;
- DbContext 内所有操作,使用同一个事务;
- 当实体存在自增时,或者 Add/AddRange 的时候主键值为空,会提前开启事务;
- 支持同步/异步方法;