简体   繁体   中英

C# Entity Framework and DB - change from smallint to int

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM