1

Due to a certain change we have to make, some columns in the db have to be changed from smallint to int and as a result, we have to change the code variables from short to int.

Since it is a pretty big change, we would like to do it in 2 steps - first change the db and only then change the code (or the other way around).

We did a small test - changed a column in a specific table from smallint to int without changing the code - the code variable is still expecting short.

When using EF to get results from the DB and assigning it to the appropriate c# class, we get the following error (which is reasonable):

"System.InvalidOperationException: The 'CountryID' property on 'TestClass' could not be set to a 'System.Int32' value. You must set this property to a non-null value of type 'System.Int16'

EDIT: similar exception raises if we first try to change the code variable to be int and working with db column as smallint:

"System.InvalidOperationException: The 'CountryID' property on 'TestClass' could not be set to a 'System.Int16' value. You must set this property to a non-null value of type 'System.Int32'

Some code and data:

  • The DB table has a column named CountryID (int, not null).
  • the matching class is:
public class TestClass
{
    public short CountryID { get; set; }
}

the modelBuilder is:

    ToTable("Country");
    // mapping an int column in the db (CountryID) to a short variable in the code (CountryID)
    Property(t => t.CountryID).HasColumnName("CountryID").IsRequired(); 

Trying to query the table with EF:

var listOfCountryIDs = dbContext.TestEntity.Where(t => t.CountryID == countryID), raises the exception.

We tried to force the model builder with adding .HasColumnType("smallint") but it didn't help. Also tried this.

Of course it works if we change both the code and the db to work with ints (or short & smallint).

Is there any way to apply this change in 2 steps? Any help would be appreciated, thanks.

1 Answer 1

0

I am afraid,you need to change datatype both at DB and Model level simultaneously. Reason is why you getting the exception mentioned in the questions is, entityframework trying to put 4 byte data from DB into 2 byte of Model, since no direct casting of this type is available hence you facing it.

As you mentioned that this is very large change, I suggest you to go one DB/One model at a time.

thanks

Sign up to request clarification or add additional context in comments.

Comments

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.