使用主键插入失败

Insert with primary key fails

我正在使用 Asp.Net Core RC2 和 EF Core 编写 Web 应用程序。当我尝试向 SQLite 数据库中插入一个新行时,该数据库应具有自动递增的主键,所有执行此插入的尝试都会导致错误:

An exception of type 'System.InvalidOperationException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code

Additional information: Unable to create or track an entity of type 'SystemIssue' because it has a null primary or alternate key value.

如果我手动向字段 "id" 添加值,则插入工作正常。

SQL

CREATE TABLE "SystemIssues" 
(
    `Id`    INTEGER PRIMARY KEY,
    `TicketNumber`  TEXT,
    `HostName`  TEXT NOT NULL,
    `CreateDate`    TEXT,
    `EndDate`   TEXT,
    `Details`   TEXT,
    `IsClosed`  INTEGER
)

型号

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace psiWebApp.Models
{
    public class SystemIssue
    {
        public string Id { get; set; }

        public string HostName { get; set; }
        public string TicketNumber { get; set; }

        public string CreateDate { get; set; }
        public string EndDate { get; set; }
        public string Details { get; set; }
        public int isClosed { get; set; }
    }
}

控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using psiWebApp.Models;
using System.Data;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace psiWebApp.Controllers
{
    public class SystemIssueController : Controller
    {
        private MyDbContext _dbcontext;

        public SystemIssueController(MyDbContext context)
        {
            _dbcontext = context;
        }

        // GET: /<controller>/
        public IActionResult Index()
        {
            var openTickets = from g in _dbcontext.SystemIssues where g.isClosed !=0 orderby g.Id select g;
            return View(openTickets.ToList());
           // return View(_dbcontext.SystemIssues.ToList());
        }

        public IActionResult Add()
        {
            return View();
        }

        //
        // POST: /SystemIssue/Add

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Add(SystemIssue systemissue)
        {
            //if (ModelState.IsValid)
            {
                // _dbcontext.Entry(systemissue).State = Microsoft.EntityFrameworkCore.EntityState.Added;
                //systemissue.Id = "6";

                systemissue.TicketNumber = "8888";
                systemissue.isClosed = 1;
                systemissue.Details = "Test Data for this host 888";
                systemissue.HostName = "server.host1";
                systemissue.CreateDate = "06/24/2016";
                // systemissue.EndDate = "06/24/2016";
                //systemissue.Id = null;
                _dbcontext.SystemIssues.Add(systemissue);
                _dbcontext.SaveChanges();
                return RedirectToAction("Index");
            }
        }
    }
}

MyDbContext

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data.Common;
using psiWebApp.Models;
using Microsoft.EntityFrameworkCore;

namespace psiWebApp.Models
{
    public class  MyDbContext : DbContext
    {
        public MyDbContext(DbContextOptions<MyDbContext> options) 
            : base(options)
        { }

        public DbSet<Contact> Contacts { get; set; }
        public DbSet<SystemIssue> SystemIssues { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<SystemIssue>().HasKey(m => m.Id);
            base.OnModelCreating(builder);
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("Filename=./psiweb.db");
        }
    }
}

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using psiWebApp.Models;
using Microsoft.Extensions.PlatformAbstractions;

namespace psiWebApp
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            var path = PlatformServices.Default.Application.ApplicationBasePath;
            services.AddEntityFrameworkSqlite().AddDbContext<MyDbContext>(optionsBuilder => optionsBuilder.UseSqlite("Filename=./psiweb.db"));

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            //loggerFactory.AddProvider(new MyFilteredLoggerProvider());

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseStatusCodePages();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "SystemIssues",
                    template: "{controller=SystemIssues}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "Dashboard",
                    template: "{controller=Dashboard}/{action=Index}");
            });
        }
    }
}

模型将 id 定义为字符串,而它应该是 int。

由于您的数据库脚本将 Id 定义为整数,因此它在模型上也应该是整数