相关的ICollection实体不能为null

时间:2018-03-29 18:38:45

标签: c# .net asp.net-mvc asp.net-core

我的模型有这个字段:

public ICollection<Guest> SecondaryGuests { get; set; }

并且还有get来计算结果:

public int TotalRSVP
{
     get
     {
         return (GuestOf == null && 
             SecondaryGuests.Any() ? RSVP + SecondaryGuests.Count() : 0);
     }
 }

当我使用CreateEdit方法时,除了抛出异常外,这工作得很好:

  

SecondaryGuests不能为空

我可以通过Edit添加include来解决此问题:

var guestToUpdate = await _context.Guests
    .Include(g => g.SecondaryGuests)
    .SingleOrDefaultAsync(g => g.ID == id);

然而,在Create方法中,我不知道如何解决这个问题。

我可以将get字段放在ViewModel中,但这会对我的索引和详细信息视图等产生大量额外的工作。我宁愿修改我的Create方法或数字如何忽略get方法上的Create

1 个答案:

答案 0 :(得分:1)

而不是使用Any()SecondaryGuestsnull时会出现错误),只需检查nullCount()

return (GuestOf == null && SecondaryGuests != null && SecondaryGuests.Count() > 0 ?
        RSVP + SecondaryGuests.Count() : 0);