本文介绍了实体框架核心2.0映射枚举到SQL Server中的tinyint引发查询异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将枚举映射到中的 smallint 时,出现以下异常OnModelCreating

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

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

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:

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

有没有办法进行这项工作,这样我所有的 enum s都不必使用4倍的空间?

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?

推荐答案

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

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

public enum TagType: byte

您需要删除

... .HasColumnType("smallint");

然后,列将自动设为tinyint,或手动进行设置:

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

.HasColumnType("tinyint"); 

这篇关于实体框架核心2.0映射枚举到SQL Server中的tinyint引发查询异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 02:30