9

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

2
  • Why can't you upgrade the database to use INTEGER for this column? Commented Aug 10, 2013 at 7:58
  • I'm only writing a maintenance programme and have concerns about side effects in the main application... Commented Aug 12, 2013 at 7:14

1 Answer 1

13

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,
    });
Sign up to request clarification or add additional context in comments.

3 Comments

I don't understand how this compiles? You have two properties with the same name.
Do you need HasColumnType("SMALLINT")? Is declare int16 not enough?
@MichaelFreidgeim, I just tested this and for me simply declaring the int16 was enough

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.