【问题标题】:Entity Framework Core 2.0 mapping int to SQL Server smallint throws exception on queryEntity Framework Core 2.0 映射 int 到 SQL Server smallint 在查询中引发异常
【发布时间】:2018-05-12 00:48:49
【问题描述】:

我在 SQL Server 中将int 属性映射到smallint。当我查询数据库时,我得到以下异常:

InvalidOperationException:发生异常时 读取属性“Tag.Count”的数据库值。预期类型 是“System.Int32”,但实际值为“System.Int16”类型

我想这样做是因为如果我在实体上使用short,我最终不得不编写额外的代码来将short 转换为int

相关代码截图:

public class Tag
{
    public int Count { get; set; }

    //Other properties
}

//In DbContext
protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Tag>().Property(m => m.Count).HasColumnType("smallint");
}

//query
var tags = await context.Tags.ToArrayAsync();

【问题讨论】:

  • 缺少最小、完整和可验证的示例:stackoverflow.com/help/mcve
  • @PhilNDeBlanc 不确定你的意思。但我会尝试一下
  • 你应该使用short而不是int作为Count属性的类型。
  • 我认为你必须使用short。如果您不想在整个代码中进行强制转换,您可以添加一个未映射的 int 属性来获取/设置您的 Count 属性并在您的代码中使用它。
  • @CodeNotFound @Valuator 抱歉,问题出在enums。发布新的question here

标签: c# entity-framework-core


【解决方案1】:

int 更改为int16,因为SMALLINT 是16 位,int 是32 位。 所以 32 位不能转换为 16 位。您也可以使用short 数据类型。

public class Tag
{
    public int16 Count { get; set; } 
    // or, 
   /* public short Count { get; set; } */

    //Other properties
}

//In DbContext
protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Tag>().Property(m => m.Count).HasColumnType("smallint");
}

//query
var tags = await context.Tags.ToArrayAsync();

【讨论】:

  • 抱歉,使用 EF Core 已经有一段时间了。问题在于enums。发布新的question here
猜你喜欢
  • 1970-01-01
  • 2020-05-29
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-19
  • 1970-01-01
相关资源
最近更新 更多