无法转换类型为“System.DBNull”的对象输入“System.String”获得所有产品后

发布于 2025-01-11 00:52:32 字数 5194 浏览 0 评论 0原文

  [HttpGet]
    public async Task<ActionResult> Get()
    {
        var GettingItemDetails = await db.wp_Posts.Join(db.wp_Postmeta,
            post => post.ID,
            meta => meta.post_id,
            (post, meta) => new { Post = post, Meta = meta })
            .Where(x => x.Post.ID > 0)
            .Where(x => x.Post.post_type == "product")
            .Where(x => x.Meta.meta_key == "_stock")
            .Select(x => new
            {
                Post_Title = x.Post.post_title,
                Meta_Key = x.Meta.meta_key,
                Meta_Value = x.Meta.meta_value,
                Product_Id = x.Post.ID,
            }
             ).ToListAsync();
        return Ok(GettingItemDetails);

        
    }

我的类

public class wp_posts
{
    [Key]
    public int ID { get; set; }
    public int post_author { get; set; } = 0;
    public DateTime post_date { get; set; } = DateTime.Now;
    public DateTime post_date_gmt { get; set; } = DateTime.Now;
    public string post_content { get; set; } = string.Empty;
    public string post_title { get; set; } = string.Empty;
    public string post_excerpt { get; set; } = string.Empty;
    public string post_status { get; set; } = string.Empty;
    public string comment_status { get; set; } = string.Empty;
    public string ping_status { get; set; } = string.Empty;
    public string post_password { get; set; } = string.Empty;
    public string post_name { get; set; } = string.Empty;
    public string to_ping { get; set; } = string.Empty;
    public string pinged { get; set; } = string.Empty;
    public DateTime post_modified { get; set; } = DateTime.Now;
    public DateTime post_modified_gmt { get; set; } = DateTime.Now;
    public string post_content_filtered { get; set; } = string.Empty;
    public int post_parent { get; set; } = 0;
    public string guid { get; set; } = string.Empty;
    public int menu_order { get; set; } = 0;
    public string post_type { get; set; } = string.Empty;
    public string post_mime_type { get; set; } = string.Empty;
    public int comment_count { get; set; } = 0;
    


}

 public class wp_postmeta
{
    [Key]
    public int meta_id { get; set; }
    public int post_id { get; set; } = 0;
    public string meta_key { get; set; } = string.Empty;
    public string meta_value { get; set; } = string.Empty;

   
}

错误我面临

ystem.InvalidCastException:无法将类型“System.DBNull”的对象转换为类型“System.String”。 在 //src/MySqlConnector/Core/Row.cs 中的 MySqlConnector.Core.Row.GetString(Int32 ordinal):第 377 行 在 //src/MySqlConnector/MySqlDataReader.cs 中的 MySqlConnector.MySqlDataReader.GetString(Int32 ordinal):第 287 行 在 lambda_method13(闭包,QueryContext,DbDataReader,ResultContext,SingleQueryResultCoordinator) 在 Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable1.AsyncEnumerator.MoveNextAsync() 在 Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable1 源,CancellationToken CancellationToken) 在 Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 源,CancellationToken CancellationToken) 在 D:\ApiDevelopment\WoocommerceApi\WoocommerceApi\Controllers\wp_postsController.cs 中的 WoocommerceApi.Controllers.wp_postsController.Get():第 24 行 在 lambda_method5( 闭包 , 对象 ) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper 映射器、ObjectMethodExecutor 执行器、对象控制器、Object[] 参数) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ControllerActionInvoker.g__Logged|12_1(ControllerActionInvoker 调用程序) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker 调用程序、任务lastTask、状态下一个、范围范围、对象状态、布尔值已完成) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed 上下文) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ControllerActionInvoker.Next(状态&下一个,范围&范围,对象&状态,Boolean&isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker 调用程序、任务lastTask、状态下一个、范围范围、对象状态、布尔值已完成) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.g__Awaited|20_0(ResourceInvoker 调用程序、任务lastTask、状态下一个、范围范围、对象状态、布尔值已完成) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.g__Logged|17_1(ResourceInvoker 调用程序) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.g__Logged|17_1(ResourceInvoker 调用程序) 在 Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(端点端点、任务 requestTask、ILogger 记录器) 在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext 上下文) 在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext 上下文) 在 Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) 在 Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext,ISwaggerProvider swaggerProvider) 在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

我想要的只是从 wp_posts 获取产品 id 和标题,并从 wp_postmeta 获取库存数量 wp_post 中的 ID 和 wp_postmeta 中的 post_id 相同,但如果我传递一个 id 它可以工作,但我想要所有产品,我仍然会收到此错误

  [HttpGet]
    public async Task<ActionResult> Get()
    {
        var GettingItemDetails = await db.wp_Posts.Join(db.wp_Postmeta,
            post => post.ID,
            meta => meta.post_id,
            (post, meta) => new { Post = post, Meta = meta })
            .Where(x => x.Post.ID > 0)
            .Where(x => x.Post.post_type == "product")
            .Where(x => x.Meta.meta_key == "_stock")
            .Select(x => new
            {
                Post_Title = x.Post.post_title,
                Meta_Key = x.Meta.meta_key,
                Meta_Value = x.Meta.meta_value,
                Product_Id = x.Post.ID,
            }
             ).ToListAsync();
        return Ok(GettingItemDetails);

        
    }

My Classes

public class wp_posts
{
    [Key]
    public int ID { get; set; }
    public int post_author { get; set; } = 0;
    public DateTime post_date { get; set; } = DateTime.Now;
    public DateTime post_date_gmt { get; set; } = DateTime.Now;
    public string post_content { get; set; } = string.Empty;
    public string post_title { get; set; } = string.Empty;
    public string post_excerpt { get; set; } = string.Empty;
    public string post_status { get; set; } = string.Empty;
    public string comment_status { get; set; } = string.Empty;
    public string ping_status { get; set; } = string.Empty;
    public string post_password { get; set; } = string.Empty;
    public string post_name { get; set; } = string.Empty;
    public string to_ping { get; set; } = string.Empty;
    public string pinged { get; set; } = string.Empty;
    public DateTime post_modified { get; set; } = DateTime.Now;
    public DateTime post_modified_gmt { get; set; } = DateTime.Now;
    public string post_content_filtered { get; set; } = string.Empty;
    public int post_parent { get; set; } = 0;
    public string guid { get; set; } = string.Empty;
    public int menu_order { get; set; } = 0;
    public string post_type { get; set; } = string.Empty;
    public string post_mime_type { get; set; } = string.Empty;
    public int comment_count { get; set; } = 0;
    


}

 public class wp_postmeta
{
    [Key]
    public int meta_id { get; set; }
    public int post_id { get; set; } = 0;
    public string meta_key { get; set; } = string.Empty;
    public string meta_value { get; set; } = string.Empty;

   
}

Error i am Facing

ystem.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.
at MySqlConnector.Core.Row.GetString(Int32 ordinal) in //src/MySqlConnector/Core/Row.cs:line 377
at MySqlConnector.MySqlDataReader.GetString(Int32 ordinal) in /
/src/MySqlConnector/MySqlDataReader.cs:line 287
at lambda_method13(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator )
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable1.AsyncEnumerator.MoveNextAsync() at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable1 source, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
at WoocommerceApi.Controllers.wp_postsController.Get() in D:\ApiDevelopment\WoocommerceApi\WoocommerceApi\Controllers\wp_postsController.cs:line 24
at lambda_method5(Closure , Object )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Logged|12_1(ControllerActionInvoker invoker)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

All I want is to get product id and title from wp_posts and get stock qty from wp_postmeta
ID in wp_post and post_id in wp_postmeta are the same but still, I get this error if I pass a single id it works but I want all products

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦开始←不甜 2025-01-18 00:52:32

通过将 Nullable 类型添加到我的模型中解决了这个问题,

 public class wp_postmeta
{
    [Key]
    public int meta_id { get; set; }
    public int? post_id { get; set; } = 0;
    public string? meta_key { get; set; } = string.Empty;
    public string? meta_value { get; set; } = string.Empty;

   
}

Json 类响应是

 [
  {
    "post_Title": "Shirt",
    "meta_Key": "_stock",
    "meta_Value": "20",
    "product_Id": 12
  },
  {
    "post_Title": "Jeans",
    "meta_Key": "_stock",
    "meta_Value": null,
    "product_Id": 13
  }
]

原来元值为 null

Solved it by Adding Nullable Type to my model Class

 public class wp_postmeta
{
    [Key]
    public int meta_id { get; set; }
    public int? post_id { get; set; } = 0;
    public string? meta_key { get; set; } = string.Empty;
    public string? meta_value { get; set; } = string.Empty;

   
}

Json Response is

 [
  {
    "post_Title": "Shirt",
    "meta_Key": "_stock",
    "meta_Value": "20",
    "product_Id": 12
  },
  {
    "post_Title": "Jeans",
    "meta_Key": "_stock",
    "meta_Value": null,
    "product_Id": 13
  }
]

Turns out meta value was null

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文