c# - 错误:实体类型需要定义主键
问题描述
我正在尝试学习有关 Entity Framework Core 的一些教程。本教程采用代码优先的方法来创建数据库。当我尝试运行第一次迁移时,此错误显示:
实体类型“值”需要定义主键。
确切的消息如下:
System.InvalidOperationException:实体类型“值”需要定义主键。Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys(IModel model) 在 Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model) 在 Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel model) 在 Microsoft.EntityFrameworkCore.Internal.SqliteModelValidator .Validate(IModel model) at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator) at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass5_0.b__1() at System.Lazy
1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy
1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) at System.Lazy 2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection。 ServiceLookup.CallSiteVisitor 2.VisitCallSite(IServiceCallSite callSite, TArgument argument) 在 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope) 在 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor1.CreateValue() at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator) at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_1(IServiceProvider p) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor
2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
1 个访问器)在 Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance() at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure1 accessor) at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func
1 个工厂)在 Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType) 在 Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType) 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor。 AddMigrationImpl(String name, String outputDir, String contextType) 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0() 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1。 b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) 实体类型“值”需要定义主键。
(有人可以编辑这个消息,因为它看起来很糟糕而且我无法修复它吗?)
我已经仔细检查了我在Value类中是否有Id属性,并且为了确定,我已经添加了 [Key] 。我还重新启动了我的笔记本电脑,因为它可能与从以前的测试会话或类似的东西运行的服务器实例有关。
我的模型课:
using System.ComponentModel.DataAnnotations;
namespace DatingApp.API.Models
{
public class Value
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
}
数据库上下文:
using DatingApp.API.Models;
using Microsoft.EntityFrameworkCore;
namespace DatingApp.API.Data
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base (options) {}
public DbSet<Value> Values {get; set;}
}
}
启动.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DatingApp.API.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace DatingApp.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(c => c.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// app.UseHsts();
}
// app.UseHttpsRedirection();
app.UseMvc();
}
}
}
和连接字符串:
{
"ConnectionStrings":
{
"DefaultConnection": "Data Source=DatingApp.db"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
我在终端写的东西:
dotnet ef migrations add InitialMigration
编辑:
D:\DatingApp\DatingApp.API>dotnet ef migrations add InitialMigration -v Using project 'D:\DatingApp\DatingApp.API\DatingApp.API.csproj'. Using startup project 'D:\DatingApp\DatingApp.API\DatingApp.API.csproj'. Writing 'D:\DatingApp\DatingApp.API\obj\DatingApp.API.csproj.EntityFrameworkCore.targets'... dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\B590\AppData\Local\Temp\tmp24D5.tmp
/verbosity:quiet /nologo D:\DatingApp\DatingApp.API\DatingApp.API.csproj 写作 'D:\DatingApp\DatingApp.API\obj\DatingApp.API.csproj.EntityFrameworkCore.targets'... dotnet msbuild /target :GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\B590\AppData\Local\Temp\tmp2B8C.tmp /verbosity:quiet /nologo D:\DatingApp\DatingApp.API\DatingApp.API.csproj dotnet build D:\DatingApp\ DatingApp.API\DatingApp.API.csproj /verbosity:quiet /nologo
Compilation succesfull. Warnings: 0 Errors: 0 Time passed: 00:00:02.25 dotnet exec --depsfile D:\DatingApp\DatingApp.API\bin\Debug\netcoreapp2.1\DatingApp.API.deps.json
--additionalprobingpath C:\Users\B590.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig D:\DatingApp\DatingApp.API\bin\Debug\netcoreapp2.1\DatingApp .API.runtimeconfig.json "C:\Program Files\dotnet\sdk\2.1.403\DotnetTools\dotnet-ef\2.1.4\tools\netcoreapp2.1\any\tools\netcoreapp2.0\any\ef.dll " 迁移添加 InitialMigration --assembly D:\DatingApp\DatingApp.API\bin\Debug\netcoreapp2.1\DatingApp.API.dll --startup-assembly D:\DatingApp\DatingApp.API\bin\Debug\netcoreapp2.1 \DatingApp.API.dll --project-dir D:\DatingApp\DatingApp.API\ --language C# --working-dir D:\DatingApp\DatingApp.API --verbose --root-namespace DatingApp.API 使用程序集'约会应用程序.API'。使用启动程序集“DatingApp.API”。使用应用程序库'D:\DatingApp\DatingApp.API\bin\Debug\netcoreapp2.1'。使用工作目录“D:\DatingApp\DatingApp.API”。使用根命名空间“DatingApp.API”。使用项目目录“D:\DatingApp\DatingApp.API\”。查找 DbContext 类...查找 IDesignTimeDbContextFactory 实现...查找应用程序服务提供者...查找 IWebHost 访问器...使用环境“开发”。在“程序”上使用来自 IWebHost 访问器的应用程序服务提供程序。找到 DbContext 'DataContext'。在项目中查找 DbContext 类...使用上下文“DataContext”。System.InvalidOperationException:实体类型“值”需要定义主键。在 Microsoft.EntityFrameworkCore.Infrastructure。
1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy
1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) at System.Lazy1.CreateValue() at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator) at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model() at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_1(IServiceProvider p) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor
2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection。 ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor
2.VisitCallSite(IServiceCallSite callSite, TArgument argument) 在 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope) 在 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance() at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure
1 个访问器)在 Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure1 accessor) at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func
1 个工厂)在 Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType) 在 Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType) 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor。 AddMigrationImpl(String name, String outputDir, String contextType) 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0() 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1。 b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) 实体类型“值”需要定义主键。
解决方案
推荐阅读
- c++ - (反)在c ++中序列化包含__uint128_t的结构
- c# - 为 c# 调用 REST API 的简单方法?
- python - 验证用户输入 Python
- amazon-web-services - AWS route53 和 DNS 设置
- javascript - 如何将谷歌地图移动到添加标记的位置
- android - android库中的异步操作,我可以使用哪个coroutineScope?
- python - 模块“选择器”没有属性“默认选择器”?
- javascript - 如何在wordpress的导航栏标题之间添加搜索栏
- xcode12 - 如何在 Xcode 12.2 中调整调试区域的高度?
- nix - 有没有办法让 pkgs 的更改渗透到整个 nix 配置中?