0

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();
5
  • Minimal, Complete and verifiable example is missing: stackoverflow.com/help/mcve Commented May 11, 2018 at 16:38
  • @PhilNDeBlanc not sure what you mean there. But I'll take a stab at it Commented May 11, 2018 at 16:42
  • Instead of int you should use short as type for Count property. Commented May 11, 2018 at 16:42
  • You'll have to use short I think. If you don't want to do casts throughout your code you could add an unmapped int property that gets/sets your Count property and use that in your code instead. Commented May 11, 2018 at 16:49
  • @CodeNotFound @Valuator Sorry, the problem is with enums. Posted new question here Commented May 11, 2018 at 17:15

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, been a while since working with EF Core. The problem is with enums. Posted new question here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.