【发布时间】: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