Blazor如何根据输入合并JSON来更新MongoDB关系



注意:提前抱歉,这是我在这里的第一个问题

我目前正在使用Blazor开发一个简单的应用程序。我已经建立了一个mongoDB数据库,其中包含标题为team和teamMembers的相关集合。我已经创建了模型、服务和控制器来处理数据库请求。.rarzor组件有一个用于添加团队的输入表单,可以按预期工作。我想更进一步,增加相关的团队成员。我能够成功地将新的团队成员发布到MongoDB数据库中的teamMembers集合中;然而,我不知道如何对团队集合执行PUT请求,以包括嵌套在团队中的团队成员。

我对C#还比较陌生,ASP.NET框架在获取与团队成员相关的输入并将其添加到团队集合中时遇到了问题。

型号Team.cs

using System;
using System.Collections.Generic;
using System.Text;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;
using System.ComponentModel.DataAnnotations;
namespace Dashboard.Shared.Models
{
public class Team
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[Required(ErrorMessage = "A Name is required")]
public string Name { get; set; }
public string Location { get; set; }
public string Type { get; set; }
[BsonRepresentation(BsonType.ObjectId)]
public List<string> TeamMembers { get; set; }
[BsonIgnore]
public List<TeamMember> TeamMemberList { get; set; }
}
}

TeamMember.cs

using System;
using System.Collections.Generic;
using System.Text;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace Dashboard.Shared.Models
{
public class TeamMember
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
public string Rank { get; set; }
public string Role { get; set; }
}
}

服务:TeamService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB.Driver;
using Dashboard.Shared.Models;
namespace Dashboard.Server.Services
{
public class TeamService
{
private readonly IMongoCollection<Team> _teams;
public TeamService(IDashboardDatabaseSettings settings)
{
var client = new MongoClient(settings.ConnectionString);
var database = client.GetDatabase(settings.DatabaseName);
_teams = database.GetCollection<Team>(settings.TeamsCollectionName);
}
public async Task<List<Team>> GetAllAsync()
{
return await _teams.Find(s => true).ToListAsync();
}
public async Task<Team> GetByIdAsync(string id)
{
return await _teams.Find<Team>(s => s.Id == id).FirstOrDefaultAsync();
}
public async Task<Team> CreateAsync(Team team)
{
await _teams.InsertOneAsync(team);
return team;
}
public async Task UpdateAsync(string id, Team team)
{
await _teams.ReplaceOneAsync(s => s.Id == id, team);
}
public async Task DeleteAsync(string id)
{
await _teams.DeleteOneAsync(s => s.Id == id);
}
}
}

TeamMemberService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB.Driver;
using Dashboard.Shared.Models;
namespace Dashboard.Server.Services
{
public class TeamMemberService
{
private readonly IMongoCollection<TeamMember> _teamMembers;
public TeamMemberService(IDashboardDatabaseSettings settings)
{
var client = new MongoClient(settings.ConnectionString);
var database = client.GetDatabase(settings.DatabaseName);
_teamMembers = database.GetCollection<TeamMember>(settings.TeamMembersCollectionName);
}
public async Task<List<TeamMember>> GetAllAsync()
{
return await _teamMembers.Find(c => true).ToListAsync();
}
public async Task<TeamMember> GetByIdAsync(string id)
{
return await _teamMembers.Find<TeamMember>(c => c.Id == id).FirstOrDefaultAsync();
}
public async Task<TeamMember> CreateAsync(TeamMember teamMember)
{
await _teamMembers.InsertOneAsync(teamMember);
return teamMember;
}
public async Task UpdateAsync(string id, TeamMember teamMember)
{
await _teamMembers.ReplaceOneAsync(c => c.Id == id, teamMember);
}
public async Task DeleteAsync(string id)
{
await _teamMembers.DeleteOneAsync(c => c.Id == id);
}
}
}

控制器:TeamController.cs

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dashboard.Server.Services;
using Dashboard.Shared.Models;
namespace Dashboard.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TeamController : ControllerBase
{
private readonly TeamService _teamService;
private readonly TeamMemberService _teamMemberService;
public TeamController(TeamService service, TeamMemberService tService)
{
_teamService = service;
_teamMemberService = tService;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Team>>> GetAll()
{
var teams = await _teamService.GetAllAsync();
return Ok(teams);
}

[HttpGet("{id:length(24)}")]
public async Task<ActionResult<Team>> GetById(string id)
{
var team = await _teamService.GetByIdAsync(id);
if (team == null)
{
return NotFound();
}
if (team.TeamMembers != null)
{
if (team.TeamMembers.Count > 0)
{
var tempList = new List<TeamMember>();
foreach (var teamMemberId in team.TeamMembers)
{
var teamMember = await _teamMemberService.GetByIdAsync(teamMemberId);
if (teamMember != null)
tempList.Add(teamMember);
}
team.TeamMemberList = tempList;
}
}
return Ok(team);
}
[HttpPost]
public async Task<IActionResult> Create(Team team)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
await _teamService.CreateAsync(team);
return Ok(team);
}
[HttpPut("{id:length(24)}")]
public async Task<IActionResult> Update(string id, Team updatedTeam)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
var queriedTeam = await _teamService.GetByIdAsync(id);
if (queriedTeam == null)
{
return NotFound();
}
await _teamService.UpdateAsync(id, updatedTeam);
return NoContent();
}
[HttpDelete("{id:length(24)}")]
public async Task<IActionResult> Delete(string id)
{
var team = await _teamService.GetByIdAsync(id);
if (team == null)
{
return NotFound();
}
await _teamService.DeleteAsync(id);
return NoContent();
}
}
}

TeamMemberController.cs

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dashboard.Server.Services;
using Dashboard.Shared.Models;
namespace Dashboard.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TeamMemberController : Controller
{
private readonly TeamMemberService _teamMemberService;
public TeamMemberController(TeamMemberService tService)
{
_teamMemberService = tService;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<TeamMember>>> GetAll()
{
var teamMembers = await _teamMemberService.GetAllAsync();
return Ok(teamMembers);
}

[HttpGet("{id:length(24)}")]
public async Task<ActionResult<TeamMember>> GetById(string id)
{
var teamMember = await _teamMemberService.GetByIdAsync(id);
if (teamMember == null)
{
return NotFound();
}
return Ok(teamMember);
}
[HttpPost]
public async Task<IActionResult> Create(TeamMember teamMember)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
await _teamMemberService.CreateAsync(teamMember);
return Ok(teamMember);
}
[HttpPut("{id:length(24)}")]
public async Task<IActionResult> Update(string id, TeamMember updatedTeamMember)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
var queriedTeamMember = await _teamMemberService.GetByIdAsync(id);
if (queriedTeamMember == null)
{
return NotFound();
}
await _teamMemberService.UpdateAsync(id, updatedTeamMember);
return NoContent();
}
[HttpDelete("{id:length(24)}")]
public async Task<IActionResult> Delete(string id)
{
var teamMember = await _teamMemberService.GetByIdAsync(id);
if (teamMember == null)
{
return NotFound();
}
await _teamMemberService.DeleteAsync(id);
return NoContent();
}
}
}

Startup.cs(仅相关服务(

public void ConfigureServices(IServiceCollection services)
{
...
services.AddScoped<TeamService>();
services.AddScoped<TeamMemberService>();
...
}

TeamFetch.rarzor

@page "/addteam"
@using System.Net.Http
@using Dashboard.Shared.Models
@inject HttpClient Http

<MatH5>Add Teams</MatH5>
<br />
<div>
<div style="float:left">
<button class="btn btn-primary" @onclick="@this.AddTeam">Add Teams</button>
</div>
</div>
<br />
@if (teamList == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class='table'>
<thead>
<tr>
<th>Name</th>
<th>Location</th>
<th>Type</th>
</tr>
</thead>
<tbody>
@foreach (var team in teamList)
{
<tr>
<td>@team.Name</td>
<td>@team.Location</td>
<td>@team.Type</td>
<td>
<button class="btn btn-success" @onclick="@this.AddTeamMember">Add Members</button>
<button class="btn btn-info" @onclick="@(async () => await EditTeam(team.Id))">Edit</button>
<button class="btn btn-danger" @onclick="@(async () => await DeleteConfirm(team.Id))">Delete</button>
</td>
</tr>
}
</tbody>
</table>
if (isAddMember)
{
<div class="modal" tabindex="-1" style="display:block" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">@modalTitle</h3>
<button type="button" class="close" @onclick="@this.closeModal">
<span aria-hidden="true">X</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="Name" class="control-label">Name</label>
<input for="Name" class="form-control" @bind=teamMember.Name />
</div>
<div class="form-group">
<label asp-for="Position" class="control-label">Position</label>
<input asp-for="Position" class="form-control" @bind=teamMember.Rank />
</div>
<div class="form-group">
<label asp-for="Role" class="control-label">Role</label>
<select asp-for="Role" class="form-control" @bind=teamMember.Role>
<option value="">-- Select Team Type --</option>
<option value="Team Leader">Team Leader</option>
<option value="Team Member">Team Member</option>
</select>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-block btn-success" @onclick="@(async () => await SaveTeamMember(team.Id))" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
}
if (isAdd)
{
<div class="modal" tabindex="-1" style="display:block" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">@modalTitle</h3>
<button type="button" class="close" @onclick="@this.closeModal">
<span aria-hidden="true">X</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="Name" class="control-label">Name</label>
<input for="Name" class="form-control" @bind=team.Name />
</div>
<div class="form-group">
<label asp-for="Location" class="control-label">Location</label>
<input asp-for="Location" class="form-control" @bind=team.Location />
</div>
<div class="form-group">
<label asp-for="Type" class="control-label">Type</label>
<select asp-for="Type" class="form-control" @bind=team.Type>
<option value="">-- Select Team Type --</option>
<option value="Ops">Ops</option>
<option value="Tech">Tech</option>
<option value="Staff/Management">Staff / Management</option>
</select>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-block btn-success" @onclick="@(async () => await SaveTeam())" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
}
if (isDelete)
{
<div class="modal" tabindex="-1" style="display:block" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">Delete Team</h3>
</div>
<div class="modal-body">
<h4>Do you want to delete this team??</h4>
<table class="table">
<tr>
<td>Name</td>
<td>@team.Name</td>
</tr>
<tr>
<td>Location</td>
<td>@team.Location</td>
</tr>
<tr>
<td>Type</td>
<td>@team.Type</td>
</tr>
</table>
</div>
<div class="modal-footer">
<button class="btn btn-danger" @onclick="@(async () => await DeleteTeam(@team.Id))" data-dismiss="modal">YES</button>
<button class="btn btn-warning" @onclick="@this.closeModal">NO</button>
</div>
</div>
</div>
</div>
}
}
@code {
private List<Team> teamList;
private Team team = new Team();
private List<TeamMember> teamMemberList;
private TeamMember teamMember = new TeamMember();
private string modalTitle { get; set; }
private Boolean isDelete = false;
private Boolean isAdd = false;
private Boolean isAddMember = false;
private string SearchString { get; set; }
protected override async Task OnInitializedAsync()
{
await GetTeam();
await GetTeamMember();
}
private async Task GetTeam()
{
teamList = await Http.GetFromJsonAsync<List<Team>>("api/team/");
}
private async Task GetTeamMember()
{
teamMemberList = await Http.GetFromJsonAsync<List<TeamMember>>("api/teammember/");
}
private void AddTeamMember()
{
teamMember = new TeamMember();
this.modalTitle = "Add Team Member";
this.isAddMember = true;
}
private void AddTeam()
{
team = new Team();
this.modalTitle = "Add Team";
this.isAdd = true;
}
private async Task EditTeam(string id)
{
team = await Http.GetFromJsonAsync<Team>("api/team/" + id);
this.modalTitle = "Edit Team";
this.isAdd = true;
}
private async Task SaveTeam()
{
if (team.Id != null)
{
await Http.PutAsJsonAsync<Team>($"api/team/{team.Id}", team);
}
else
{
await Http.PostAsJsonAsync<Team>("api/team/", team);
}
this.isAdd = false;
await GetTeamMember();
}
/*THIS IS WHERE I'M NOT SURE WHAT TO DO*/
private async Task SaveTeamMember(string id)
{
if (teamMember.Id != null)
{
await Http.PutAsJsonAsync<TeamMember>($"api/teammember/{teamMember.Id}", teamMember);
}
else
{
await Http.PostAsJsonAsync<TeamMember>("api/teammember/", teamMember);
}
this.isAddMember = false;
await GetTeam();
}
private async Task DeleteConfirm(string Id)
{
team = await Http.GetFromJsonAsync<Team>("api/team/" + Id);
this.isDelete = true;
}
private async Task DeleteTeam(string Id)
{
await Http.DeleteAsync("api/team/" + Id);
this.isDelete = false;
await GetTeam();
}
private void closeModal()
{
this.isAdd = false;
this.isDelete = false;
}
}

**编辑1:**我忘了放表单输入的JSON输出

Json团队

{
"id": "5fcdc04f126ca946e44a257b",
"name": "Team 2",
"location": "Office Building 3",
"type": "Staff/Management",
"teamMembers": null,
"teamMemberList": null
}

团队成员Json

{
"id": "5fcd816d8275e9e054e54ac7",
"name": "John Smith",
"rank": "Tech Lead",
"role": "Team Leader"
}

我的问题是如何构建PUT请求,在该请求中我可以将创建的团队成员mongoDB对象ID嵌套到";团队成员";在Team.Json中列出以创建关系?我可以单独完成它们,但无法在创建团队成员时找到合并它们的代码。

我可以在PostMan中手动完成,我会得到预期的返回结果

预期回报

{
"id": "5fcdc04f126ca946e44a257b",
"name": "Team 2",
"location": "Office Building 3",
"type": "Staff/Management",
"teamMembers": [
"5fcd816d8275e9e054e54ac7"
],
"teamMemberList": [
{
"id": "5fcd816d8275e9e054e54ac7",
"name": "John Smith",
"rank": "SGT",
"role": "Team Leader"
}
]
}

更新

我能够成功地修复我的一些代码,以接受输入并合并团队和团队成员的输入;然而,我现在有一个新问题。

如果还没有团队成员被添加到团队中,那么我可以成功地构建所需的JSON,将单个团队成员添加到团队;然而,如果团队中已经存在teamMember,我将努力开发代码,将新的teamMember添加到现有的teamMember中。我将把更新后的代码放在下面,以帮助更好地解释我的新问题

更新的TeamFetch.rarzor

private async Task SaveTeamMember(string teamid)
{
if (teamMember.Id != null)
{
await Http.PutAsJsonAsync<TeamMember>($"api/teammember/{teamMember.Id}", teamMember);
}
else
{
var postTeam = teamMember;
var postTeamRequest = new HttpRequestMessage(HttpMethod.Post, "api/teammember")
{
Content = JsonContent.Create(postTeam)
};
var postTeamResponse = await Http.SendAsync(postTeamRequest);
postTeamResponse.EnsureSuccessStatusCode();
string postrespBody = await postTeamResponse.Content.ReadAsStringAsync();
JObject memberpost = JObject.Parse(postrespBody);
var memberid = memberpost["id"].ToString();
HttpResponseMessage response = await Http.GetAsync($"api/team/" + teamid);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
JObject teamreturn = JObject.Parse(responseBody);
var id = teamreturn["id"].ToString();
var name = teamreturn["name"].ToString();
var location = teamreturn["location"].ToString();
var type = teamreturn["type"].ToString();
var members = teamreturn["teamMembers"].ToString();
if (members == "")
{
Team payload = new Team
{
Id = id,
Name = name,
Location = location,
Type = type,
TeamMembers = new List<string> {
memberid
}
};
await Http.PutAsJsonAsync<Team>($"api/team/{teamid}", payload);
}
else
{
/*This is where I need assistance now*/
Team payload = new Team
{
Id = id,
Name = name,
Location = location,
Type = type,
TeamMembers = new List<string>{
members,
memberid
}
};
await Http.PutAsJsonAsync($"api/team/{teamid}", payload);
}
}
this.isAddMember = false;
await GetTeam();
}

在上面,我在我挣扎的地方发表了一条评论。如何将一个字符串添加到一个直到执行get请求才知道它是列表的变量中?不确定这是否是正确的提问方式,但这就是我现在的困境,哈哈。

提前感谢您的建议!

这最终使我能够合并单个团队成员以及多个团队成员已经存在时的用户输入。

private async Task SaveTeamMember(string teamid)
{
if (teamMember.Id != null)
{
await Http.PutAsJsonAsync<TeamMember>($"api/teammember/{teamMember.Id}", teamMember);
}
else
{
var postTeam = teamMember;
var postTeamRequest = new HttpRequestMessage(HttpMethod.Post, "api/teammember")
{
Content = JsonContent.Create(postTeam)
};
var postTeamResponse = await Http.SendAsync(postTeamRequest);
postTeamResponse.EnsureSuccessStatusCode();
string postrespBody = await postTeamResponse.Content.ReadAsStringAsync();
JObject memberpost = JObject.Parse(postrespBody);
var memberid = memberpost["id"].ToString();
HttpResponseMessage response = await Http.GetAsync($"api/team/" + teamid);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
JObject teamreturn = JObject.Parse(responseBody);
var id = teamreturn["id"].ToString();
var name = teamreturn["name"].ToString();
var location = teamreturn["location"].ToString();
var type = teamreturn["type"].ToString();
var members = teamreturn["teamMembers"].ToString();
if (members == "")
{
Team payload = new Team
{
Id = id,
Name = name,
Location = location,
Type = type,
TeamMembers = new List<string> {
memberid
}
};
await Http.PutAsJsonAsync<Team>($"api/team/{teamid}", payload);
}
else
{
List<string> newmembers = new List<string>();
foreach (var member in teamreturn["teamMembers"])
{
newmembers.Add(member.ToString());
}
newmembers.Add(memberid);
Team payload = new Team
{
Id = id,
Name = name,
Location = location,
Type = type,
TeamMembers = newmembers
};
await Http.PutAsJsonAsync($"api/team/{teamid}", payload);
}
}
this.isAddMember = false;
await GetTeamMember();
}

相关内容

  • 没有找到相关文章