Entity Framework: How to map the Int64 field to the Int32 db column?

advertisements

There is an int ID column in a MS SQL database table, but the entity class contains a long ID field, and I get the following message in the context:

"An exception occured while reading a database value. The expected type was 'System.Int64' but the actual value was of type 'System.Int32'."

I've already tried to set the column type:

modelBuilder.Entity<XXXEntity>()
            .Property(b => b.Id)
            .HasColumnName("XXXId")
            .HasColumnType("int");

but that does not work. What's the right solution?

I cannot change neither the entity class nor the db table.


You should map Int64 into bigint on SQL server:

 modelBuilder.Entity<XXXEntity>()
            .Property(b => b.Id)
            .HasColumnName("XXXId")
            .HasColumnType("bigint");

UPDATE: Since your SQL column data type is int, you should change your Id datatype inside XXXEntity class to Int32