Blazor Server - System.InvalidCastException: Unable to cast object of type 'System.Double' to type 'System.Single'.

Cenk 956 Reputation points
2023-01-25T06:21:35.1233333+00:00

Hi,

In my Blazor server application, I am trying to get the records from RazerReconciliation table as follows. I couldn't figure out why I am getting this error.

public async Task<List<RazerReconciliations>> GetOldReconsAsync()
{
      var result = await _oyunPalasContext.RazerReconciliation.ToListAsync();
      return result;
}

Here is the model;

public class RazerReconciliations
    {
        public string? PID { get; set; }
        public string? ProductName { get; set; }
        public float ProductAmount { get; set; }
        public Guid ReferenceNo { get; set; }
        public int Quantity { get; set; }
        public DateTime TransactionDateTime { get; set; }
        public string? Explanation { get; set; }

    }

Here is the table:

CREATE TABLE [dbo].[RazerReconciliation](
	[PID] [nvarchar](50) NULL,
	[ProductName] [nvarchar](200) NULL,
	[ProductAmount] [float] NULL,
	[ReferenceNo] [uniqueidentifier] NOT NULL,
	[Quantity] [int] NOT NULL,
	[TransactionDateTime] [datetime] NULL,
	[Explanation] [varchar](200) NULL
) ON [PRIMARY]

Here is the Context:

public virtual DbSet<RazerReconciliations> RazerReconciliation { get; set; } = null!;
modelBuilder.Entity<RazerReconciliations>().HasNoKey();
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
698 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,404 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,309 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 112.7K Reputation points
    2023-01-25T06:39:49.8133333+00:00

    According to https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings, try using float in SQL and double in C#.

    By the way, maybe decimal datatypes are more suitable.

    0 comments No comments