[英]ASP.NET Core Web API - FirstOrDefault not giving required result in Entity Framework
In ASP.NET Core 5 Web API, I have these models:在 ASP.NET Core 5 Web API 中,我有这些模型:
public abstract class AuditableBaseEntity
{
[Key]
public long Id { get; set; }
}
public class Merchant : AuditableBaseEntity
{
public string MerchantName { get; set; }
public string AccountNumber { get; set; }
public string UserName { get; set; }
}
Then these are the queries:然后这些是查询:
Get the UserName of the Logged in User
获取登录用户的用户名
var userName = _userResolverService.GetUserName();
Get the id of the merchant
获取商家id
var merchantId = _context.merchants
.Where(u => u.UserName == userName)
.Select(m => m.Id)
.FirstOrDefault();
I expect to get the Id
of a particular merchant using the logged in UserName
, but I got zero (0) result我希望使用登录的
UserName
获得特定商家的Id
,但我得到零 (0) 结果
When I debut userName
returns the correct result.当我首次亮相
userName
返回正确的结果。 The problem is with getting the merchantId
.问题在于获取
merchantId
。
How do I get this resolved?我该如何解决这个问题?
Thanks谢谢
When you execute only a part of your command, what do you get:当您只执行部分命令时,您会得到什么:
var merchant = _context.merchants.Where(u => u.UserName == userName).FirstOrDefault();
var merchantId = merchant.Id;
If merchant == null, it will then return the default value for int (id), which is 0.如果商家 == null,则返回 int (id) 的默认值,即 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.