c# - Entity Framework Core 2.0 将枚举映射到 SQL Server 中的 tinyint 在查询时抛出异常

标签 c# entity-framework-core

当我尝试将 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/

相关文章:

c# - 如何在 ASP.NET Core 6.0 Web API 中读取 Azure App 服务的应用程序设置

c# - ASP.NET - 在 session 变量中存储类 - 它是如何工作的(内存)?

c# - 键盘按键捕获

c# - 有没有办法在 Entity Framework Core 中映射临时表?

asp.net-core - 无法跟踪实体类型 '' 的实例,因为已在跟踪键值为 '{Id: 13}' 的另一个实例

c# - 如何将 SqlBulkCopy 与 DataTable 中的二进制数据 (byte[]) 一起使用?

c# - .NET 循环完整性 101

c# - 即使 Entity Framework 核心中的模型没有任何更新,DateTime 属性也会导致新的迁移更新

c# - EF核心: cannot insert object with foreign key using ID properties (only navigation properties work)

asp.net-mvc - Entity Framework Core 与 .Net 4.7 MVC 身份问题