记开发个人图书收藏清单小程序开发(六)Web开发

时间:2024-05-01 16:25:04

Web页面开发暂时是没有问题了,现在开始接上Ptager.BL的DB部分。

首先需要初始化用户和书房信息。因为还没有给其他多余的设计,所以暂时只有个人昵称和书房名称。

添加 Init Razor Pages(/Pages/Shelves/Init) 。

/Pages/Shelves/Init.cshtml

 @page
@model InitModel
@{
ViewData["Title"] = "Shelf Init";
} <nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a asp-page="/Index">Home</a></li>
<li class="breadcrumb-item"><a asp-page="/My Books/Index">My Books</a></li>
<li class="breadcrumb-item active" aria-current="page">Bookcase Init</li>
</ol>
</nav> <form method="post">
<div class="form-group form-group-lg">
<label asp-for="Input.NickName"></label>
<input class="form-control form-control-lg" asp-for="Input.NickName" autocomplete="off">
</div>
<div class="form-group form-group-lg">
<label asp-for="Input.ShelfName"></label>
<input class="form-control form-control-lg" asp-for="Input.ShelfName" autocomplete="off">
</div>
<div class="form-group text-right">
<button class="btn btn-warning btn-lg" type="submit">Save</button>
</div>
</form>

现在去实现底层Repo的部分。

记开发个人图书收藏清单小程序开发(六)Web开发

需要在BL层添加基本的底层代码:

记开发个人图书收藏清单小程序开发(六)Web开发

在PTager.BL.Core层增加DataContract、Models和Repos Interface。

记开发个人图书收藏清单小程序开发(六)Web开发

暂时还没有用到查询,所以只需要增加Init Model和Repo Interface就好。

新增Shelf.InitSpec Model文件:

Shelf.InitSpec.cs

 namespace PTager.BL
{
public partial class Shelf
{
public class InitSpec
{
public string NickName { get; set; }
public string ShelfName { get; set; }
}
}
}

Install Package Newtonsoft.Json

新增_module扩展文件:

_module.cs

 namespace PTager.BL
{
[System.Diagnostics.DebuggerNonUserCode]
public static partial class extOC
{
public static string ToJson<T>(this T me) where T : class
=> JsonConvert.SerializeObject(me);
}
}

并且引用Projects:Ptager.BL

新增IShelfRepo:

IShelfRepo.cs

 using System.Threading.Tasks;

 namespace PTager.BL
{
using M = Shelf;
public interface IShelfRepo
{
Task Init(M.InitSpec spec);
}
}

在PTager.BL.Data层增加Store和Repos的实现。

引用Projects:Ptager.BL和PTager.BL.Core,并且添加Nuget Package:System.Data.SqlClient、Microsoft.EntityFrameworkCore.Relational

记开发个人图书收藏清单小程序开发(六)Web开发

其中Store的内容是模仿Linq to SQL的分层做的,但没那么高的性能,勉强够用而已。

RepoBase.cs

 namespace PTager.BL.Data
{
public class RepoBase
{
protected readonly BLDbContext _context;
public RepoBase(BLDbContext context)
{
_context = context;
}
}
}

_module.cs

 namespace PTager.BL.Data
{
[System.Diagnostics.DebuggerNonUserCode]
public static partial class extBL { }
}

BLDbContext.cs

 using System.Threading.Tasks;

 namespace PTager.BL.Data.Store
{
public class BLDbContext : DbContext
{
public BLDbContext(DbContextOptions<BLDbContext> options)
: base(options)
{
this.ChangeTracker.AutoDetectChangesEnabled = false;
} #region { Functions } #endregion #region { Actions } public async Task Shelf_Init(string json)
=> await this.ExecuteMethodCallAsync(nameof(Shelf_Init), args: json); #endregion
}
}

BLDbContext.ext.cs(这是目前代码中最脏的部分了,找时间需要优化这个部分)

 using Microsoft.EntityFrameworkCore;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks; namespace PTager.BL.Data.Store
{
public static partial class extUSDContext
{
public static IQueryable<T> CreateMethodCallQuery<T>(this DbContext me, MethodBase method, string schema = "svc")
where T : class
=> me.CreateMethodCallQuery<T>(method, schema, null);
public static IQueryable<T> CreateMethodCallQuery<T>(this DbContext me, MethodBase method, string schema = "svc", params object[] args)
where T : class
{
var hasArgs = args != null && args.Length > ;
//var fields = typeof(T).GetType().ToSelectFields();
var sql = $"select * from {schema}.{method.Name.Replace("_", "$")}(";
if (hasArgs) sql += string.Join(", ", args.Select(x => $"@p{args.ToList().IndexOf(x)}"));
sql += ")";
me.Database.SetCommandTimeout(TimeSpan.FromMinutes());
return hasArgs ? me.Set<T>().FromSql(sql, args) : me.Set<T>().FromSql(sql);
} public static async Task<string> ExecuteMethodCallAsync(this DbContext me, string methodName)
=> await me.ExecuteMethodCallAsync(methodName, null);
public static async Task<string> ExecuteMethodCallAsync(this DbContext me, string methodName, params object[] args)
=> await me.ExecuteMethodCallAsync(methodName, false, args);
public static async Task<string> ExecuteMethodCallAsync(this DbContext me, string methodName, bool lastOutput, params object[] args)
{
var hasArgs = args != null && args.Length > ;
var sql = $"svc.{methodName.Replace("_", "$")} ";
if (!hasArgs)
{
if (lastOutput == false)
{
await me.Database.ExecuteSqlCommandAsync(sql);
return string.Empty;
}
}
else
{
sql += string.Join(", ", args.Select(x => $"@p{args.ToList().IndexOf(x)}"));
if (lastOutput == false)
{
await me.Database.ExecuteSqlCommandAsync(sql, args);
return string.Empty;
}
sql += ", ";
}
sql += " @result output";
var parameters = args.Select(x => new SqlParameter($"@p{args.ToList().IndexOf(x)}", x)).ToList();
var outParam = new SqlParameter("@result", SqlDbType.VarChar, int.MaxValue)
{
Value = string.Empty,
Direction = ParameterDirection.Output
};
parameters.Add(outParam);
me.Database.SetCommandTimeout(TimeSpan.FromMinutes());
await me.Database.ExecuteSqlCommandAsync(sql, parameters.ToArray());
return outParam.Value.ToString();
}
}
}

好了,基础已建好,新增ShelfRepo的实现。

ShelfRepo.cs

 namespace PTager.BL.Data.Repos
{
using System.Threading.Tasks;
using PTager.BL.Data.Store;
using M = Shelf;
public class ShelfRepo : RepoBase, IShelfRepo
{
public ShelfRepo(BLDbContext context) : base(context)
{
} public async Task Init(M.InitSpec spec)
=> await _context.Shelf_Init(spec.ToJson());
}
}

在WebUI的Project中,引用新增的三个底层项目,并在Statup.cs的ConfigureServices中注册IShelfRepo的依赖和BL DB的连接注册:

     services.AddDbContext<BLDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("BLConnection")));
services.AddScoped<IShelfRepo, ShelfRepo>();

当然,这个时会报错的,因为我们并没有在appsetting中添加这个DB Connection。

修改后的appsettings.json

 {
"ConnectionStrings": {
"DefaultConnection": "Server=.\\SQL2017;Database=PTager;Trusted_Connection=True;MultipleActiveResultSets=true",
"BLConnection": "Server=.\\SQL2017;Database=PTagerBL;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}

接下来需要去新建DB的Script实现这个Shelf_Init功能了。