efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Value cast error in a projection

Open tNRevan opened this issue 1 year ago • 0 comments

I have a simple entity with a short column (SQL server smallint) and int column. Then I am doing a simple projection and multiplying those two columns (which does an implicit cast) and fails.

void Main(string[] args)
{
    var results = new EfContext().Set<Variation>()
        .Select(o => new
        {
            Mileage = o.Duration * o.Mileage,
        })
        .ToList();
}

[Table("Tb_Variace")]
public class Variation
{
    [Key]
    [Column("Id V")]
    public int Id { get; set; }

    [Column("DTL")]
    public short Duration { get; set; }

    [Column("KMLIMIT")]
    public int Mileage { get; set; }
}

public class EfContext : DbContext
{
    public DbSet<Variation> Variations => Set<Variation>();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("xxx", o => o.UseCompatibilityLevel(120));
    }
}

The thrown exception is:

System.InvalidCastException
  HResult=0x80004002
  Message=Unable to cast object of type 'System.Int32' to type 'System.Int16'.
  Source=Microsoft.Data.SqlClient
  StackTrace:
   at Microsoft.Data.SqlClient.SqlBuffer.get_Int16()
   at Microsoft.Data.SqlClient.SqlDataReader.GetInt16(Int32 i)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at EfCoreTest.Program.Main(String[] args) in ...

Include provider and version information

EF Core version: 8.0.6 Database provider: Microsoft.EntityFrameworkCore.Sqlite 8.0.6 Database: SQL Server 2014 Target framework: .NET 8.0 Operating system: Windows 10 IDE: Visual Studio 2022 17.10.1

tNRevan avatar Jun 26 '24 21:06 tNRevan