locked
Unable to cast object of type 'System.Byte' to type 'System.Int32' problems RRS feed

  • Question

  • User-2006371901 posted

    I have a .NetCore Blazor App, morphed from the stock weather forecast service that comes with it, whereas I have players who log their play info, but once a player logs in and wants to look at their info via the stock “Fetch Data” link, the user cannot proceed as an Unable to cast object of type ‘System.Byte’ (not sure from what model property this stems from ) to type ‘System.Int32’. The user, upon registering , and logging in, is able to create/post a record (as it inserts into the database), but coming back to view their post, renders the Unhandled Exception.

    In my wagtrakservice.cs class, I have the lineup intact:

    ///////

    public async Task<List<Wagtrak>>

    GetForecastAsync(string strCurrentUser)

    {

    // Get Weather Forecasts – player records

    return await _context.Wagtrak

    // Only get entries for the current logged in user

    /// UserName is weatherforecast version, put Username inside Wagtrak table

    .Where(x => x.UserName == strCurrentUser)

    // Use AsNoTracking to disable EF change tracking

    // Use ToListAsync to avoid blocking a thread

    .AsNoTracking().ToListAsync();

    }

    public Task<Wagtrak>

    CreateForecastAsync(Wagtrak objWagtrak)

    {

    _context.Wagtrak.Add(objWagtrak);

    _context.SaveChanges();

    return Task.FromResult(objWagtrak);

    }

    public Task<bool>

    UpdateForecastAsync(Wagtrak objWagtrak)

    {

    var ExistingWagtrak =

    _context.Wagtrak

    .Where(x => x.WID == objWagtrak.WID)

    .FirstOrDefault();

    if (ExistingWagtrak != null)

    {

    ExistingWagtrak.Gamedate =

    objWagtrak.Gamedate;

    ExistingWagtrak.TeamH =

    objWagtrak.TeamH;

    ExistingWagtrak.TeamV =

    objWagtrak.TeamV;

    ExistingWagtrak.ptsHome =

    objWagtrak.ptsHome;

    ExistingWagtrak.ptsVisitor =

    objWagtrak.ptsVisitor;

    ExistingWagtrak.LinePlay =

    objWagtrak.LinePlay;

    ExistingWagtrak.DaPlay =

    objWagtrak.DaPlay;

    ExistingWagtrak.LineClose =

    objWagtrak.LineClose;

    ExistingWagtrak.Payout =

    objWagtrak.Payout;

    ExistingWagtrak.Summary =

    objWagtrak.Summary;

    _context.SaveChanges();

    }

    ////////

    DDL for the SQL table:

    CREATE TABLE [dbo].[Wagtrak](

    [WID] [int] IDENTITY(1,1) NOT NULL,

    [UserName] [varchar](50) NULL,

    [Gamedate] [date] NULL,

    [ptsHome] [tinyint] NULL,

    [ptsVisitor] [tinyint] NULL,

    [LinePlay] [numeric](18, 1) NULL,

    [TotalPlay] [numeric](18, 1) NULL,

    [Payout] [int] NULL,

    [Summary] [nvarchar](max) NULL,

    [TeamH] [varchar](20) NULL,

    [TeamV] [varchar](20) NULL,

    [DaPlay] [varchar](20) NULL

    ///////////

    the context class has this lineup with appears to be correct assigns from model to Entity properties:

    ///////////

    protected override void OnModelCreating(ModelBuilder modelBuilder)

    {

    modelBuilder.HasAnnotation("ProductVersion", "2.2.0-rtm-35687");

    modelBuilder.Entity<Wagtrak>(entity =>

    {

    /* see endtoendcontext.cs endtoend2 pjc for carinventorysho to mirror how we call

    the primary key (WID) in this case */

    entity.HasKey(e => e.WID);

    entity.Property(e => e.WID).HasColumnName("WID");

    entity.Property(e => e.Gamedate).HasColumnType("datetime");

    entity.Property(e => e.TeamH).HasMaxLength(20)

    .IsUnicode(false);

    entity.Property(e => e.TeamV).HasMaxLength(20)

    .IsUnicode(false);

    entity.Property(e => e.ptsHome).HasColumnType("int")

    .IsUnicode(false);

    entity.Property(e => e.ptsVisitor).HasColumnType("int")

    .IsUnicode(false);

    entity.Property(e => e.LineClose).HasColumnType("decimal(18, 0)")

    .IsUnicode(false);

    entity.Property(e => e.LinePlay).HasColumnType("decimal(18, 0)")

    .IsUnicode(false);

    entity.Property(e => e.Payout).HasColumnType("int")

    .IsUnicode(false);

    entity.Property(e => e.DaPlay).HasMaxLength(20)

    .IsUnicode(false);

    /// HasColumnType entity.Property(e => e.Summary).HasMaxLength(1000);

    entity.Property(e => e.Summary).HasColumnType("nvarchar(max)")

    .IsUnicode(false);

    entity.Property(e => e.UserName).HasMaxLength(50);

    });

    OnModelCreatingPartial(modelBuilder);

    }

    //////////

    ..since the Summary column is a nvarchar(max) , I believe this is how it should be assigned …

    Thanks in advance

    Ned

    Friday, June 12, 2020 1:06 AM

Answers

  • User-474980206 posted

    Your column mapping is wrong. You define sql columns ptsHome and ptsVisitor as byte (tinyint) but map them to int in EF.  Just make them match.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 12, 2020 2:30 PM

All replies

  • User-2006371901 posted

    Here is partial stack trace, as it points to the aforementioned methods listed in my initial post:

    An unhandled exception occurred while processing the request.
    InvalidCastException: Unable to cast object of type 'System.Byte' to type 'System.Int32'.
    Microsoft.Data.SqlClient.SqlBuffer.get_Int32()

    Stack Query Cookies Headers Routing
    InvalidCastException: Unable to cast object of type 'System.Byte' to type 'System.Int32'.
    Microsoft.Data.SqlClient.SqlBuffer.get_Int32()
    Microsoft.Data.SqlClient.SqlDataReader.GetInt32(int i)
    lambda_method(Closure , QueryContext , DbDataReader , ResultContext , int[] , ResultCoordinator )
    Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable<T>+AsyncEnumerator.MoveNextAsync()
    Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync<TSource>(IQueryable<TSource> source, CancellationToken cancellationToken)
    Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync<TSource>(IQueryable<TSource> source, CancellationToken cancellationToken)
    EndToEnd.Data.WagtrakService.GetForecastAsync(string strCurrentUser) in WagtrakService.cs+
    return await _context.Wagtrak
    EndToEnd.Pages.FetchData.OnInitializedAsync() in FetchData.razor.cs
    +
    forecasts = await @Service.GetForecastAsync(user.Identity.Name);

    Friday, June 12, 2020 1:18 AM
  • User1120430333 posted

    If I were you, I would search the code of the entire solution and find out what variable or object property is defined as Byte. I would also review database table schemas and find out what column is defined as Byte. It's the only way you're going to find out what is causing the problem.

    Friday, June 12, 2020 2:53 AM
  • User-474980206 posted

    Your column mapping is wrong. You define sql columns ptsHome and ptsVisitor as byte (tinyint) but map them to int in EF.  Just make them match.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 12, 2020 2:30 PM