主要是参考Dapper 的实现方式,freesql 也是支持根据IDbConnection IDbTransaction来创建的。下面的代码只是演示怎么使用,没有封装写的很简单,提供了个查询和使用事务添加的方法。
public class BookAppService : ApplicationService, IBookAppService { private readonly IDbContextProvider<BookStoreFreeSqlDbContext> _dbContextProvider; public BookAppService(IDbContextProvider<BookStoreFreeSqlDbContext> dbContextProvider) { _dbContextProvider = dbContextProvider; } public virtual async Task<object> GetBook() { var dbconn = (await _dbContextProvider.GetDbContextAsync()).Database.GetDbConnection(); var dbTransaction = (await _dbContextProvider.GetDbContextAsync()).Database.CurrentTransaction?.GetDbTransaction(); return await dbconn.Select<Models.Books>().ToListAsync(); } public virtual async Task<object> AddBook() { var dbconn = (await _dbContextProvider.GetDbContextAsync()).Database.GetDbConnection(); var dbTransaction = (await _dbContextProvider.GetDbContextAsync()).Database.CurrentTransaction?.GetDbTransaction(); Logger.LogWarning($"dbTransaction:{dbTransaction.Connection.ConnectionString}"); var book = new Models.Books { Name = "1994", Type = BookType.Dystopia, PublishDate = new DateTime(1949, 6, 8), Price = 19.84f }; dbTransaction.Insert<Models.Books>().AppendData(book).ExecuteAffrows(); book = new Models.Books { Name = "1995", Type = BookType.Dystopia, PublishDate = new DateTime(1949, 6, 8), Price = 19.84f }; dbTransaction.Insert<Models.Books>().AppendData(book).ExecuteAffrows(); return "执行成功"; } }