简体   繁体   中英

Unable to cast object of type 'System.DBNull' to type 'System.String' On getting all Products

  [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.SingleQueryingEnumerable 1.AsyncEnumerator.MoveNextAsync() at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable 1 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.Exec ute(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(Ht tpContext 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM