简体   繁体   English

ASP.NET 核心 Web API - FirstOrDefault 在实体框架中没有给出所需的结果

[英]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.

相关问题 如何使用实体框架在 ASP.NET Core Web API 中添加过滤器 - How to add filters in ASP.NET Core Web API using Entity Framework 使用ASP.NET Web API和实体框架进行API版本控制 - API Versioning with ASP.NET Web API and Entity Framework 在 ASP.NET 核心 Web ZDB974238714CA8DE634A7CE1DZ08A 中避免与 Linq 的实体重复 - Avoid entity duplication with Linq in ASP.NET Core Web API 在ASP.NET Web API和实体框架中搜索数据 - Search data in asp.net web api and Entity Framework 什么是最好的带有Asp.Net Web Api的实体框架或存储库 - What is preferable Entity Framework or Repository with Asp.Net Web Api breezejs和ASP.NET Web Api OData中的实体框架继承 - Entity Framework Inheritance in breezejs and ASP.NET Web Api OData 使用实体框架的ASP.NET Web API 2 CRUD操作 - ASP.NET Web API 2 CRUD Operation with Entity Framework ASP.NET Core MVC 1.3 Web API + Entity Framework,我无法按名称搜索数据库,但可以按 ID - ASP.NET Core MVC 1.3 Web API + Entity Framework, I can't search a database by name, but I can by id ASP.NET 中的 Web 页面和实体框架给出错误我正在努力解决 - Web page in ASP.NET and Entity Framework giving error I am struggling to resolve 使用2实体框架ASP.Net API - Working with 2 Entity Framework ASP.Net API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM