实体框架Core 2.0将枚举枚举到SQL Server中的tinyint会在查询时抛出异常

Mic*_*ida 6 c# entity-framework-core

当我尝试将一个映射enumsmallintin 时,我得到以下异常OnModelCreating:

InvalidCastException:无法将类型为"System.Byte"的对象强制转换为"System.Int32".

我想这样做是因为在SQL Server中a int是4个字节而a tinyint是1个字节.

相关代码:实体:

namespace SOMapping.Data
{
    public class Tag
    {
        public int Id { get; set; }

        public TagType TagType { get; set; }
    }

    public enum TagType
    {
        Foo,
        Bar
    }
}
Run Code Online (Sandbox Code Playgroud)

的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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

查询:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我有没有办法让这项工作成功,这样我就不必每次使用4倍的空间了enum

dNP*_*dNP 11

枚举的基本类型和列的类型必须相同.从更改枚举的基本类型开始:

public enum TagType: byte
Run Code Online (Sandbox Code Playgroud)

你需要删除

... .HasColumnType("smallint");
Run Code Online (Sandbox Code Playgroud)

然后列将是automaticaly tinyint,或者设置为manualy:

.HasColumnType("tinyint"); 
Run Code Online (Sandbox Code Playgroud)