加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 实体框架Core 2.0将枚举枚举到SQL Server中的tinyint会引

发布时间:2020-12-16 01:26:50 所属栏目:百科 来源:网络整理
导读:当我尝试在OnModelCreating中将枚举映射到smallint时,我得到以下异常: InvalidCastException: Unable to cast object of type ‘System.Byte’ to type ‘System.Int32’. 我想这样做是因为在SQL Server中,int是4个字节而tinyint是1个字节. 相关代码: 实体
当我尝试在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
    }
}

的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");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读