加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 实体框架代码优先 – 将smallint和整数转换为int32

发布时间:2020-12-15 07:54:13 所属栏目:百科 来源:网络整理
导读:我正在为数据库工作一个小型服务工具.我的问题是,由于上次更新,一些smallint-colums必须更改为整数. public class TEST{ public int ID { get; set; } //public Int16 ID { get; set; } public string TEST { get; set; }} 我将类型从Int16更改为int.一切正
我正在为数据库工作一个小型服务工具.我的问题是,由于上次更新,一些smallint-colums必须更改为整数.
public class TEST
{
    public int ID { get; set; }
    //public Int16 ID { get; set; }
    public string TEST { get; set; }

}

我将类型从Int16更改为int.一切正常,除了我不能再使用旧版本的数据库了. Exception类似于“System.Int32 expect,found Typ System.Int16”.

有没有办法将所有smallint和整数强制转换为int32?

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

我试图在模型构建器中强制执行:

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

例外:

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

解决方法

我找到了解决问题的方法!我必须在我的模型中使用Int16并使用模型构建器将colum-type设置为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而没有异常(即使数字> gt; 32767):

var lQry = (from b in ctData.TEST
    select new
    {
        ID = (int)b.ID,});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读