[开源] .NET数据库ORM类库 Insql (2)

Create Common DbContext

public class SqliteDbContext<T> : DbContext where T : class { public SqliteDbContext(DbContextOptions<SqliteDbContext<T>> options) : base(options) { } protected override void OnConfiguring(DbContextOptions options) { var configuration = options.ServiceProvider.GetRequiredService<IConfiguration>(); //T type mapping to insql.xml type options.UseSqlResolver<T>(); options.UseSqlite(configuration.GetConnectionString("sqlite")); } }

Create Domain Service

public interface IUserService { IEnumerable<UserInfo> GetUserList(string userName,Gender? userGender); } public class UserService : IUserService { private readonly DbContext dbContext; //T is UserService public UserService(SqliteDbContext<UserService> dbContext) { this.dbContext = dbContext; } public IEnumerable<UserInfo> GetUserList(string userName, Gender? userGender) { return this.dbContext.Query<UserInfo>(nameof(GetUserList), new { userName, userGender }); } }

Create Service.insql.xml

创建 UserService.insql.xml 文件并且修改这个文件的属性为嵌入式文件类型 . insql type 与 UserService 类型对应.

<insql type="Example.Domain.Services.UserService,Example.Domain" > <sql> select user_id as UserId,user_name as UserName,user_gender as UserGender from user_info </sql> <select> <include refid="selectUserColumns" /> <where> <if test="userName != null"> <bind value="'%' + userName + '%'" /> user_name like @likeUserName </if> <if test="userGender != null "> and user_gender = @userGender </if> </where> order by user_id </select> </insql>

Add Insql

public void ConfigureServices(IServiceCollection services) { services.AddInsql(); services.AddScoped(typeof(DbContextOptions<>)); services.AddScoped(typeof(SqliteDbContext<>)); services.AddScoped<IUserService, UserService>(); }

Use Domain Service

public class ValuesController : ControllerBase { private readonly IUserService userService; public ValuesController(IUserService userService) { this.userService = userService; } [HttpGet] public ActionResult<IEnumerable<string>> Get() { var list = this.userService.GetUserList("11", Domain.Gender.M); } }

@有兴趣的同学可以尝试一下。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpxpgs.html