开发者社区> 问答> 正文

EF核心表格不会解析Enum并保持为0

使用EF核心的asp.net核心MVC项目,我有一个名为Message的对象,该对象具有一个称为Service的ENUM。尝试将消息添加到数据库(SQL Server)时,它保持为0。

有任何想法吗?

讯息类别:

using System;
using System.ComponentModel.DataAnnotations;

namespace AutoMatcher.Models
{
    public class Message
    {
        [Key]
        public int MessageId { get; set; }
        public string UserId { get; set; }
        public int Likes { get; set; }
        public Service Service { get; set; }
        public DateTime Time { get; set; }
        public ApplicationUser User { get; set; }

        public Message()
        {

        }
    }
}
枚举

namespace AutoMatcher.Models
{
    public enum Service
    {
        Badoo ,
        Tinder,
        Grinde
    }
}
AppDbContext:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace AutoMatcher.Models
{
    public class AppDbContext : IdentityDbContext<ApplicationUser>
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<Message>().Property(m => m.Service).HasConversion<int>();
            builder.Entity<ApplicationUser>().HasMany<Message>(m => m.Messages).WithOne(u => u.User).IsRequired();
            base.OnModelCreating(builder);
        }

        public DbSet<Message> Messages { get; set; }
    }
}
移民:

 migrationBuilder.CreateTable(
                name: "Messages",
                columns: table => new
                {
                    MessageId = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    UserId = table.Column<string>(nullable: false),
                    Likes = table.Column<int>(nullable: false),
                    Service = table.Column<int>(nullable: false),
                    Time = table.Column<DateTime>(nullable: false)
                },
这是提交我想要的数据的形式:

@model Message
@using Models
@inject UserManager<ApplicationUser> signIn

@{
    ViewData["Title"] = "Dashboard";
    Layout = "~/Views/Shared/_Layout.cshtml";

}

    <h1>Dashboard @ViewBag._userId </h1>

    <form asp-action="Schedule" asp-controller="Actions">

        <input asp-for="Likes">
        <select asp-items="Html.GetEnumSelectList<Service>()"></select>
        <input  type="datetime-local" asp-format="{0:yyyy-MM-dd}" class="form-control" />
        <button type="submit">Start</button>

</form>

这是添加后的数据库快照:

展开
收起
祖安文状元 2020-01-05 14:32:51 373 0
1 条回答
写回答
取消 提交回答
  • 缺少asp

    <select asp-for="Service" asp-items="Html.GetEnumSelectList<Service>()"></select>
    
    2020-01-05 14:33:01
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
神龙云服务器产品及技术深度解析 立即下载
弹性创造价值:基于ECS的最佳性价比实践解析 立即下载
又快又稳:阿里云下一代虚拟交换机解析 立即下载

相关镜像