Entity Framework Core 2.0 mapping enum to tinyint in SQL Server throws exception on query

泄露秘密 提交于 2019-12-10 13:15:58

问题


I get the following exception when I try to map an enum to smallint in OnModelCreating:

InvalidCastException: Unable to cast object of type 'System.Byte' to type 'System.Int32'.

I want to do this because in SQL Server an int is 4 bytes while a tinyint is 1 byte.

Relevant code: Entity:

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);
        }
    }
}

Query:

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();
        }
    }
}

Is there a way I can make this work so that I don't have to use 4 times as much space with all my enums?


回答1:


Base type of enum and type of column must be same. Start from changing base type for your enum:

public enum TagType: byte

And your need remove

... .HasColumnType("smallint");

then column would be automaticaly tinyint, or set it manualy:

.HasColumnType("tinyint"); 


来源:https://stackoverflow.com/questions/50297148/entity-framework-core-2-0-mapping-enum-to-tinyint-in-sql-server-throws-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!