You need to enable JavaScript to run this app. 现有SQL Server自增主键表下EF Core提示需定义主键的问题
优惠活动
大模型
产品
解决方案
定价
更多

现有SQL Server自增主键表下EF Core提示需定义主键的问题

问题描述

我正在学习ASP.NET Core RESTful API开发,现有一个SQL Server数据库,其中包含一张feedback表,该表有一个IDENTITY(1,1) PRIMARY KEY id列。

模型代码

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics.CodeAnalysis;

namespace Feedback_RESTful_API.Models
{
    public class Feedback
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
}

DbContext代码

using Feedback_RESTful_API.Models;
using Microsoft.EntityFrameworkCore;

namespace Feedback_RESTful_API.Data
{
    public class ApiContext : DbContext
    {
        public DbSet<Feedback> Feedbacks { get; set; }

        public ApiContext(DbContextOptions<ApiContext> options) : base(options)
        {
        }
    }
}

控制器代码

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Feedback_RESTful_API.Models;
using Feedback_RESTful_API.Data;

namespace Feedback_RESTful_API.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class FeedbackController : ControllerBase
    {
        private readonly ApiContext _context;

        public FeedbackController(ApiContext context)
        {
            _context = context;
        }

        [HttpPost]
        public JsonResult Create(Feedback feedback)
        {
            //Add the new entry
            _context.Feedbacks.Add(feedback);
            //Save the db
            _context.SaveChanges();
            //Return response
            return new JsonResult(Ok(feedback));
        }
    }
}

错误信息

System.InvalidOperationException: The entity type 'Feedback' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'.

解决方案

问题核心在于Feedback模型的Id属性没有公共访问修饰符,默认是私有状态,EF Core无法识别该属性作为主键。

修复步骤

  1. 给Id属性添加public修饰符:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

额外优化(针对已有数据库场景)

如果不想依赖数据注解,可以在ApiContext中通过Fluent API显式配置主键和自增规则:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Feedback>()
        .HasKey(f => f.Id);
    modelBuilder.Entity<Feedback>()
        .Property(f => f.Id)
        .UseIdentityColumn(); // 对应SQL Server的IDENTITY(1,1)规则
}

同时,控制器的Create方法可以优化为更符合REST规范的写法:

[HttpPost]
public ActionResult<Feedback> Create(Feedback feedback)
{
    _context.Feedbacks.Add(feedback);
    _context.SaveChanges();
    return CreatedAtAction(nameof(GetFeedback), new { id = feedback.Id }, feedback);
}

内容的提问来源于stack exchange,提问作者Tyler Mason

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 00:07:08