Entity Framework Core 2.0 mapping int to SQL Server smallint throws exception on query

c# entity-framework-core

Question

I mapped an int property to smallint in SQL Server. When I query the database, I get the following exception:

InvalidOperationException: An exception occurred while reading a database value for property 'Tag.Count'. The expected type was 'System.Int32' but the actual value was of type 'System.Int16'

I want to do it this way because if I use a short on the Entity, I end up having to write extra code to cast short to int.

Snapshot of relevant code:

public class Tag
{
    public int Count { get; set; }

    //Other properties
}

//In DbContext
protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Tag>().Property(m => m.Count).HasColumnType("smallint");
}

//query
var tags = await context.Tags.ToArrayAsync();
1
0
5/11/2018 4:38:01 PM

Popular Answer

Change int to int16 as SMALLINT is 16 bits and int is 32 bits. So 32 bits can't be converted to 16 bits. You can use short datatype also.

public class Tag
{
    public int16 Count { get; set; } 
    // or, 
   /* public short Count { get; set; } */

    //Other properties
}

//In DbContext
protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Tag>().Property(m => m.Count).HasColumnType("smallint");
}

//query
var tags = await context.Tags.ToArrayAsync();
2
5/11/2018 4:48:49 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow