Entity Framework Code First - Cast smallint and integer to int32

21,168

I found a solution for my problem! I have to use Int16 in my Model and use the modelbuilder to set the colum-type to smallint:

public class TEST
{
    public Int16 ID { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<TEST>().HasKey(a => new { a.ID});
    modelBuilder.Entity<TEST>()
    .Property(p => p.ID)
    .HasColumnType("SMALLINT");
    base.OnModelCreating(modelBuilder);
}

Now I can cast the property to int without the exception (even with numbers > 32767):

var lQry = (from b in ctData.TEST
    select new
    {
        ID = (int)b.ID,
    });
Share:
21,168
Dust258
Author by

Dust258

Updated on July 09, 2022

Comments

  • Dust258
    Dust258 about 2 years

    Im working on a small service tool for a database. My problem is that due the last update, some smallint-colums had to be be changed into integer.

    public class TEST
    {
        public int ID { get; set; }
        //public Int16 ID { get; set; }
        public string TEST { get; set; }
    
    }
    

    I changed the type from Int16 to int. Everything works fine, except that I can't use it with the old Version of the Database anymore. The Exception is something like "System.Int32 expected, found Typ System.Int16".

    Is there a way to cast all smallint and integer to int32?

    Any ideas? My Environment: EntityFramework 5.0.0 .NET 4.5 FirebirdClient 3.0.2.0

    I tried to force a cast in the modelbuilder:

            modelBuilder.Entity<TEST>()
            .Property(p => p.ID)
            .HasColumnType("smallint");
    

    Exception:

    error 2019: Member Mapping specified is not valid. The type 'Edm.Int32[Nullable=False,DefaultValue=]' of member 'ID' in Typ 'ContextRepository.TEST' is not compatible with 'FirebirdClient.smallint[Nullable=False,DefaultValue=,StoreGeneratedPattern=Identity]' of member 'SCHLUESSEL' in type 'CodeFirstDatabaseSchema.BUNDLAND'

    Make the ID Int16 and then casting everything to smallint (HasColumnType("int")) works fine but would give me exceptions with numbers bigger than 31767(smallint max)...

  • michaelmsm89
    michaelmsm89 almost 9 years
    I don't understand how this compiles? You have two properties with the same name.
  • Michael Freidgeim
    Michael Freidgeim over 6 years
    Do you need HasColumnType("SMALLINT")? Is declare int16 not enough?
  • Eric K
    Eric K almost 5 years
    @MichaelFreidgeim, I just tested this and for me simply declaring the int16 was enough