【问题标题】:The entity type requires a primary key to be defined - A primary key is the ONLY thing that's defined实体类型需要定义主键 - 主键是唯一定义的东西
【发布时间】:2019-10-24 17:56:19
【问题描述】:

我正在尝试将模型添加到我一直在从事的项目中,今天我遇到了一个问题,每次我尝试添加迁移时都会收到错误“实体类型'_____'需要定义主键”。该模型有一个名为“ID”的属性,我尝试向其添加 [Key] 属性,我什至尝试删除除 ID 属性之外的所有内容,但仍然无法正常工作。

这是模型:

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

namespace APD_Remastered_Ideas.Models
{
    public class TestModel
    {
        [Key]
        public int Id;
        public string address { get; set; }
    }
}

编辑:我也尝试过自己编写迁移:

using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;

namespace APD_Remastered_Ideas.Data.Migrations
{
    public partial class addTestModelToDb : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
            name: "TestModel",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_TestModel", x => x.Id);
            });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
            name: "TestModel");
        }
    }
}

我还尝试在 SSMS 中手动创建表。在我所有的其他项目中,以这种方式添加模型仍然有效。但是在这个项目中,我无法添加任何内容。

有谁知道我在这里做错了什么?

【问题讨论】:

    标签: c# asp.net-core entity-framework-core


    【解决方案1】:

    原来我忘了在 Id 属性后面加上 {get; set; }。这是修正后的模型:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace APD_Remastered_Ideas.Models
    {
        public class TestModel
        {
            [Key]
            public int Id { get; set; }
            public string address { get; set; }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 2021-11-27
      • 2018-08-13
      • 2019-09-13
      • 1970-01-01
      • 2022-11-19
      • 1970-01-01
      相关资源
      最近更新 更多