显示外键值列表Asp Net Web Api

时间:2019-06-01 08:19:05

标签: c# entity-framework asp.net-web-api

JsonError

在我的Gym管理应用程序上工作时,我遇到了与客户模型有关的数据收集问题。

问题与以下型号有关:

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请求时,从Payment中返回所有客户数据,包括与客户ID相关的所有付款。杰森导致邮递员的格式不正确,错过了付款清单。

这就是我尝试在控制器中执行此操作的方式

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

1 个答案:

答案 0 :(得分:0)

尝试:

var payments = await _context.Payment.Where(p => p.ClientId == client.Id).ToListAsync();

您应该使用Id来选择实体,而不是整个实体。

UPD:

尝试在[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
        );

    ...
}