c# - 显示外键值列表 Asp Net Web Api
问题描述
在我的健身房管理应用程序上工作时,我遇到了显示与客户端模型相关的数据集合。
该问题与以下模型有关:
public class Client
{
[Key]
public int Id { get; set; }
public int CardId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string PersonalInfo => "ID: " + CardId + ": " + Name + " " + Surname;
public int? GymEntries { get; set; }
public int? MartialArtsEntries { get; set; }
public int? GymEntriesLeft { get; set; }
public int? MartialArtsEntriesLeft { get; set; }
public DateTime? ClientJoined { get; set; }
public DateTime? SubscriptionExpires { get; set; }
public int? SubscriptionId { get; set; }
public virtual Subscription Subscription { get; set; }
public bool? IsDeleted { get; set; }
public virtual ICollection<Payment> Payments { get; set; }
}
public class Payment
{
[Key]
public int Id { get; set; }
public int ClientId { get; set; }
public virtual Client Client { get; set; }
public int? SubscriptionId { get; set; }
public virtual Subscription Subscription { get; set; }
public int CashRegistered { get; set; }
public string AdditionalInformation { get; set; }
public DateTime? PaymentRegistered { get; set; }
public DateTime? SubscriptionExpires { get; set; }
}
一切正常,直到我希望我的客户端控制器在给定 get/id 请求时返回所有客户端数据,包括与来自付款的客户端 ID 相关的所有付款。Postman 中的 Json 结果没有返回正确的格式,它错过了付款列表。
这就是我尝试在控制器中执行此操作的方式
[HttpGet("{id}")]
public async Task<ActionResult<Client>> GetClient(int id)
{
var client = await _context.Client.FindAsync(id);
var subscription = await _context.Subscription.FindAsync(client.SubscriptionId);
var payments = await _context.Payment.Where(p => p.Client == client).ToListAsync();
client.Subscription = subscription;
client.Payments = payments;
if (client == null)
{
return NotFound();
}
if (client.IsDeleted == true)
{
return NotFound();
}
return client;
}
解决方案
试试看:
var payments = await _context.Payment.Where(p => p.ClientId == client.Id).ToListAsync();
您应该使用Id
' 来选择实体,而不是整个实体。
升级版:
尝试在您的班级中[JsonIgnore]
设置public virtual Client Client { get; set; }
属性Payment
。防止 json 序列化程序无限循环。
您还可以在将实体转换为 JSON 时停止由于代理而导致的自引用循环,如下所示:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc()
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
...
}
推荐阅读
- python - re.search() 和 re.match() 的结果相同,但比较运算符不同
- javascript - Electron/Node.js:从 REST 响应中提取文件并保存到本地磁盘
- shortcut - 如何在 Vimium 中将一个键重新映射到另一个键
- google-apps-script - 检查文件是否存在于特定文件夹中 - Google 表格
- javascript - 如何在 Azure 通信服务中使用 AzureLogger
- typescript - 如何在我的 Typescript 代码中导入 CheckboxChangeEvent
- c# - .Net 5,Appsettings.json 在 Program.cs 中不可用?
- ios - 将项目水平附加到 tableView 单元格中,但不会填满所有空间
- python - 返回按数组字典中的值排序的键
- angular - 角度编译错误组件中的预期参数