【发布时间】: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