Entity Framework Code First - Cast smallint and integer to int32

柔情痞子 提交于 2020-05-14 18:03:19

问题


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


回答1:


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,
    });


来源:https://stackoverflow.com/questions/18107080/entity-framework-code-first-cast-smallint-and-integer-to-int32

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!