代码之家  ›  专栏  ›  技术社区  ›  Unbreakable

在连接表中找不到值时,如何从LINQ中获取NULL

  •  0
  • Unbreakable  · 技术社区  · 9 年前

    public class Referral
    {
        public Referral()
        {
            Instances = new Collection<Instance>();
        }
        [Key]
        public int ReferralId { get; set; }
        public int CandidateId { get; set; }
        public ICollection<Instance> Instances { get; set; }
    }
    

    public class Instance
    {
        [Key]
        public int InstanceId { get; set; }
        public string ReferralStatus { get; set; }
        public int ReferralId { get; set; }
        public string ReferrerId { get; set; }
    }
    

    下面是我的控制器操作

      [HttpPost]
      public JsonResult CheckForExistingReferral(ReferralViewModel viewModel)
      {
         bool hasPreviousRequest = false;
         var candidateId = User.Identity.GetUserId();
         var referral = _context.Referrals
        .Where(r => (r.CandidateId == candidateId) && r.Instances
        .Any(e => (e.ReferrerId != null) && (e.ReferralStatus == "Referred")));
              // some logic
            }
    

    截至目前,实例表中没有数据。我在推荐表中有一些数据。

    推荐表:

    ReferralId      CandidateId
    
    1                    3
    

    NO DATA
    

    问题:为什么我的LINQ查询不返回NULL。因为没有匹配的最终结果记录。我希望上面的LINQ查询返回NULL。

    1 回复  |  直到 9 年前
        1
  •  1
  •   Worthy7    9 年前

    实际上,你需要说在最后返回记录。否则,您只是在进行查询。

    var referral = _context.Referrals
        .Where(r => (r.CandidateId == candidateId) && r.Instances
        .Any(e => (e.ReferrerId != null) && (e.ReferralStatus == "Referred")))
        .FirstOrDefault();
    

    referral != null .