当我尝试在OnModelCreating中将枚举映射到smallint时,我得到以下异常: InvalidCastException: Unable to cast object of type ‘System.Byte’ to type ‘System.Int32’. 我想这样做是因为在SQL Server中,int是4个字节
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
}
}
的DbContext:
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();
}
}
}
我有没有办法让这项工作成为可能,所以我不需要使用所有枚举空间的4倍空间?
枚举的基本类型和列的类型必须相同.从更改枚举的基本类型开始:
public enum TagType: byte
你需要删除
... .HasColumnType("smallint");
然后列将是automaticaly tinyint,或者设置为manualy:
.HasColumnType("tinyint");
