使用主键插入失败

时间:2016-06-25 15:51:10

标签: sqlite asp.net-core asp.net-core-mvc entity-framework-core asp.net-core-1.0

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

  

类型' System.InvalidOperationException'的例外情况发生在Microsoft.EntityFrameworkCore.dll中但未在用户代码中处理

     

其他信息:无法创建或跟踪类型为' SystemIssue'的实体。因为它有一个空主键或备用键值。

如果我手动将值添加到字段" 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}");
            });
        }
    }
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

当模型应为int时,模型的id被定义为字符串。