Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First - Cast smallint and integer to int32

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)...

like image 974
Dust258 Avatar asked Aug 07 '13 15:08

Dust258


1 Answers

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,
    });
like image 118
Dust258 Avatar answered Sep 22 '22 09:09

Dust258