Код: Выделить всё
MyProject/MyProject.Client/Components/Application/PostsBrowser.razor.csКод: Выделить всё
public partial class PostsBrowser : ComponentBase {
...
[Inject]
public ClientDbAccess DbAccess { get; set; } = null!;
private string SearchTerm = "";
public async Task GetPostsOfCurrentPage_Async() {
var search = new ClientDbAccess.GetPostsByCriteriaParams( bodyPattern: this.SearchTerm );
IEnumerable posts = await this.DbAccess.GetPostsByCriteria_Async( search );
return posts;
}
}
Код: Выделить всё
MyProject/MyProject.Client/Services/DbAccess_Posts.csКод: Выделить всё
public partial class ClientDbAccess {
...
public class GetPostsByCriteriaParams( string bodyPattern ) {
public string BodyPattern { get; } = bodyPattern;
};
public async Task GetPostsByCriteria_Async( GetPostsByCriteriaParams parameters ) {
HttpResponseMessage msg = await this.Http.PostAsJsonAsync( "Post/GetByCriteria", parameters );
msg.EnsureSuccessStatusCode();
IEnumerable? ret = await msg.Content.ReadFromJsonAsync();
if (ret is null) {
throw new InvalidDataException("Could not deserialize IEnumerable");
}
return ret;
}
}
Код: Выделить всё
MyProject/MyProject/Controllers/Post.csКод: Выделить всё
[ApiController]
[Route("[controller]")]
public class PostController : ControllerBase {
private readonly ServerDbAccess DbAccess;
public PostController(ServerDbAccess dbAccess) {
this.DbAccess = dbAccess;
}
...
[HttpPost("GetByCriteria")]
public async Task GetByCriteria_Async(
ClientDbAccess.GetPostsByCriteriaParams parameters ) {
using IDbConnection dbCon = await this.DbAccess.ConnectDb_Async();
return await this.DbAccess.GetPostsByCriteria_Async(dbCon, parameters);
}
}
Код: Выделить всё
MyProject/MyProject/Data/DbAccess_Posts.csКод: Выделить всё
public partial class ServerDbAccess {
public class PostEntryData {
public long Id;
public DateTime Created;
public string Body = "";
public async Task CreatePost_Async(IDbConnection dbCon, ServerDbAccess dbAccess) {
return new PostObject(
id: this.Id,
created: this.Created,
body: this.Body
);
}
}
...
private (string sql, IDictionary sqlParams) GetPostsByCriteriaSql(ClientDbAccess.GetPostsByCriteriaParams parameters ) {
string sql = $"SELECT * FROM Posts AS MyPosts ";
var sqlParams = new Dictionary();
if (!string.IsNullOrEmpty(parameters.BodyPattern)) {
sql += "WHERE MyPosts.Body LIKE REPLACE(REPLACE(REPLACE(@Body, '[', '[[]'), '_', '[_]'), '%', '[%]')";
sqlParams["@Body"] = $"%{parameters.BodyPattern}%";
}
return (sql, sqlParams);
}
public async Task GetPostsByCriteria_Async(
IDbConnection dbCon,
ClientDbAccess.GetPostsByCriteriaParams parameters ) {
if (parameters.PostsPerPage == 0) {
return Enumerable.Empty();
}
(string sql, IDictionary sqlParams) = this.GetPostsByCriteriaSql(parameters, false);
return await dbCon.QueryAsync(
sql, new DynamicParameters(sqlParams)
);
}
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... t-specific
Мобильная версия