当我尝试将 enum
映射到 OnModelCreating
中的 smallint
时出现以下异常:
InvalidCastException: Unable to cast object of type 'System.Byte' to type 'System.Int32'.
我想这样做是因为在 SQL Server 中 int
是 4 个字节,而 tinyint
是 1 个字节。
相关代码: 实体:
namespace SOMapping.Data
{
public class Tag
{
public int Id { get; set; }
public TagType TagType { get; set; }
}
public enum TagType
{
Foo,
Bar
}
}
数据库上下文:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace SOMapping.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Tag>().Property(m => m.TagType).HasColumnType("smallint");
base.OnModelCreating(builder);
}
}
}
查询:
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using SOMapping.Data;
namespace SOMapping.Controllers
{
public class HomeController : Controller
{
private ApplicationDbContext _applicationDbContext;
public HomeController(ApplicationDbContext applicationDbContext)
{
_applicationDbContext = applicationDbContext;
}
public IActionResult Index()
{
var tags = _applicationDbContext.Tags.ToArray();
return View();
}
}
}
有没有一种方法可以使我的所有 enum
都不必使用 4 倍的空间?
最佳答案
枚举的基本类型和列的类型必须相同。 从更改枚举的基本类型开始:
public enum TagType: byte
你需要删除
... .HasColumnType("smallint");
然后列将自动为 tinyint,或手动设置:
.HasColumnType("tinyint");
关于c# - Entity Framework Core 2.0 将枚举映射到 SQL Server 中的 tinyint 在查询时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50297148/