【问题标题】:I got empty collection when i execute linq where conamnd by comparing Guid当我通过比较 Guid 执行 linq where conamnd 时,我得到了空集合
【发布时间】:2022-08-17 01:10:07
【问题描述】:
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 结果 我得到的结果不是空的。 我无法解决这个问题。
调用方方法:

 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();
    }
  • 如果您声明接收者和发送者不为空,则很难在您的问题中确定。

标签: c# sql-server linq entity-framework-core


【解决方案1】:

尝试这个:

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

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


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多