实体框架代码优先-将smallint和integer转换为int32 [英] Entity Framework Code First - Cast smallint and integer to int32

查看:104
本文介绍了实体框架代码优先-将smallint和integer转换为int32的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发用于数据库的小型服务工具。我的问题是,由于最近一次更新,必须将一些smallint-colums更改为整数。

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

}

我将类型从Int16更改为int。一切正常,除了我不能再与旧版本的数据库一起使用了。异常类似于 System.Int32预期,发现Typ.System.Int16。

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

是否可以将所有smallint和integer转换为int32?

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

有什么想法吗?我的环境:EntityFramework 5.0.0 .NET 4.5 FirebirdClient 3.0.2.0

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");

例外:


错误2019:指定的成员映射无效。类型 ContextRepository.TEST中成员 ID的类型 Edm.Int32 [Nullable = False,DefaultValue =]与成员的 FirebirdClient.smallint [Nullable = False,DefaultValue =,StoreGeneratedPattern = Identity]不兼容类型为'CodeFirstDatabaseSchema.BUNDLAND'的'SCHLUESSEL'

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'

使ID为Int16,然后将所有内容强制转换为smallint(HasColumnType( int)) )效果很好,但会给我一个例外,它的数字大于31767(smallint max)...

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

推荐答案

我找到了一个解决方案我的问题!我必须在模型中使用Int16并使用modelbuilder将colum-type设置为smallint:

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

现在,我可以毫无例外地将属性转换为int了(即使数字> 32767):

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

这篇关于实体框架代码优先-将smallint和integer转换为int32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆