-
Notifications
You must be signed in to change notification settings - Fork 858
DbContext
28810 edited this page Mar 20, 2019
·
30 revisions
FreeSql.DbContext 实现类似 EFCore 的使用方法,每个 DbContext 是以事务的方式存在,最终通过 SaveChanges 方法提交事务。
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()) {
id = await ctx.Songs.Insert(new Song { }).ExecuteIdentityAsync();
var item = await ctx.Songs.Select.Where(a => a.Id == id).FirstAsync();
throw new Exception("回滚,不提交事务");
}
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 内第一个添加、删除、或修改的操作,会开启事务;
- DbContext 内所有操作,使用同一个事务;
- 可多次执行 SaveChanges 方法,执行完后事务销毁,直到下一次事务开启;
- DbContext 每个实例是独立的,事务支持异步方法;