c# - 按 id 从数据库中加载行
问题描述
我有两种方法试图根据 Id 从数据库加载记录。
这些是我的方法:
private List<Cliente> GetCLienti(int clienteId) //to load Clients from DB
{
var tuttiClienti = _db.tboSottoClienti//Not sure if this query works
.Where(c => c.Id_cliente == clienteId)
.FirstOrDefaultAsync();
//var tuttiClienti = _db.tboClienti.ToList();
return tuttiClienti; //I need to return LIST
}
private List<SottoCliente> GetSottoCliente(clienteId)
{
var tuttiSottoClienti = _db.tboSottoClienti.ToList();
return tuttiSottoClienti;
}
这是在视图中显示它的方法:
public IActionResult CaricaSottoCliente(int clienteId)
{
ViewBag.Cliente = GetCLienti();
ViewBag.SottoCliente = GetSottoCliente();
return View();
}
这是我的看法:
<table class="table table-hover">
<tr>
<th>Id</th>
<th>Nome</th>
<th>Cognome</th>
<th>Azienda</th>
<th>Cellulare</th>
</tr>
@foreach (GestioneAtivita.Models.SottoCliente sottoCliente in ViewBag.SottoCliente)
{
<tr>
<td>@sottoCliente.Id</td>
<td>@sottoCliente.Nome</td>
<td>@sottoCliente.Cognome</td>
<td>@sottoCliente.Azienda</td>
<td>@sottoCliente.Cellulare</td>
</tr>
}
</table>
<p><b>Cliente List</b></p>
<table class="table table-hover">
<tr>
<th>Id</th>
<th>Code</th>
<th>Name</th>
<th>Enrollment No</th>
</tr>
@foreach (GestioneAtivita.Models.Cliente cliente in ViewBag.Cliente)
{
<tr>
<td>@cliente.Nome</td>
<td>@cliente.Cognome</td>
<td>@cliente.Nome_azienda</td>
<td>@cliente.Cellulare</td>
</tr>
}
</table>
最后,这就是我将 ID 从另一个视图传递给控制器的方式:
<td>
@Html.ActionLink("Sotto Clienti", "CaricaSottoCliente", new { clienteId = item.Id }, new { @class = "btn btn-outline-success" })
</td>
如何List
从GetCLienti(int clienteId)
方法中返回 a ?有什么建议么?提前致谢!
解决方案
您正在使用FirstOrDefaultAsync()
但您没有使用await
它。您的方法都不是async
用FirstOrDefault()
. 但是作为您的方法作为返回类型,List<Cliente>
您应该使用.ToList()
如下所示。
private List<Cliente> GetCLienti(int clienteId) //to load Clients from DB
{
var tuttiClienti = _db.tboSottoClienti//Not sure if this query works
.Where(c => c.Id_cliente == clienteId)
.ToList();
//var tuttiClienti = _db.tboClienti.ToList();
return tuttiClienti; //I need to return LIST
}
您需要将clienteId
值传递给GetCLienti
它有参数。
public IActionResult CaricaSottoCliente(int clienteId)
{
ViewBag.Cliente = GetCLienti(clienteId);
ViewBag.SottoCliente = GetSottoCliente();
return View();
}
推荐阅读
- c - 使用指向数组的指针计算字数的程序
- r - UseMethod 中的 Plotly/orca 错误(“plotly_build”)
- vue.js - 如何解决 vue.js 安装的问题
- visual-studio-code - VSCODE 找不到默认构建任务
- wordpress - Wordpress 不显示我的自定义帖子类型帖子
- swift - 日期不断回到 UTC,而不是在它所在的语言环境中保持格式
- java - 更改音频文件中的音高、速度、混响或全部,然后将其保存在 android
- asp.net-core - 如何在标签上显示“.SetDefaultKeyLifetime(TimeSpan.FromDays())”的剩余天数?ASP.NET 核心 5.0
- variables - 如何引用在函数中生成的变量以在 Cypress 中对其执行 .contains()?
- angular - 在 Azure devops 中构建 Angular 应用程序 Docker 文件时失败