首页 > 解决方案 > 显示外键值列表 Asp Net Web Api

问题描述

json错误

在我的健身房管理应用程序上工作时,我遇到了显示与客户端模型相关的数据集合。

该问题与以下模型有关:

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;
}

标签: c#entity-frameworkasp.net-web-api

解决方案


试试看:

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
        );

    ...
}

推荐阅读