通过比较Guid执行linq where conamnd时得到空集合

zfycwa2u  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(152)
public ServiceResponce Write(Guid senderID, Guid reciverID, string body)
    {
        Message message = new Message
        {
            Body = body
        };

        var reciver = context.Users.Where(c => c.Id == reciverID).Single();
        var sender = context.Users.Where(c => c.Id == senderID).Single();

        message.Sender = sender;
        message.Reciver = reciver;
        context.SaveChanges();

        return new ServiceResponce();
    }

我得到了空序列的异常。我从HTTPContext.Users.FindFirstValue(ClaimTypes.NameIdentifier)得到了Guid id结果,但得到的结果不是null。我无法解决此问题。
调用方方法:

public IActionResult Wright(Guid reciverID,string body)
    {
        var userID = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
        var neededID = Guid.Parse(userID);
        _chatService.Write(neededID, reciverID, body);
        return Ok();
    }
vmdwslir

vmdwslir1#

试试这个:

public ServiceResponce Write(...)
{
    ...
    var reciver = context.Users.Where(c => c.Id == reciverID).SingleOrDefault();
    var sender = context.Users.Where(c => c.Id == senderID).SingleOrDefault();

    if(reciver == null || sender ==null)
    {
       //Log??
       return null;
    }
    ...
    
}

public IActionResult Wright(Guid reciverID,string body)
{
    var userID = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);

    // If you really want to put the validation logic here
    Guid neededID;   
    if (!Guid.TryParse(userId, out var neededID))
    {
       //Log?
       return BadRequest();
    }

    if(_chatService.Write(neededID, reciverID, body) == null)
       return BadRequest();
    return Ok();
}

相关问题