错误:实体类型需要定义主键

时间:2018-10-31 20:47:41

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

我正在尝试遵循有关Entity Framework Core的一些教程。本教程采用代码优先的方法来创建数据库。当我尝试运行第一次迁移时,此错误显示:

  

实体类型“值”要求定义主键。

确切的消息如下:

  

System.InvalidOperationException:实体类型“值”需要一个   要定义的主键。在   Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys(IModel   型号)   Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel   型号)   Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel   型号)   Microsoft.EntityFrameworkCore.Internal.SqliteModelValidator.Validate(IModel   型号)   Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext   上下文,IConventionSetBuilder ConventionSetBuilder,IModelValidator   验证者)   Microsoft.EntityFrameworkCore.Infrastructure.ModelSource。<> c__DisplayClass5_0.b__1()   在System.Lazy 1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy 1.ExecutionAndPublication(LazyHelper   executionAndPublication,布尔值useDefaultConstructor)   System.Lazy 1.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参数)在   Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite   scopedCallSite,ServiceProviderEngineScope范围)   Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.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参数)在   Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite   scopedCallSite,ServiceProviderEngineScope范围)   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)
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](IInfrastructure 1 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   名称,字符串outputDir,字符串contextType)位于   Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String   名称,字符串outputDir,字符串contextType)位于   Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration。<> c__DisplayClass0_1。<。ctor> b__0()   在   Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase。<> c__DisplayClass3_0`1.b__0()   在   Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(操作   操作),实体类型“值”需要定义一个主键。

(有人可以编辑此味精,因为它看起来很糟糕,我无法修复?)

我已经仔细检查了我在 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; } 
    }
}

DbContext:

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;}
    }
}

Startup.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:安静/ nologo   D:\ DatingApp \ DatingApp.API \ DatingApp.API.csproj       dotnet版本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   文件\ 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 \-语言C#--working-dir D:\ DatingApp \ DatingApp.API --verbose --root-namespace DatingApp.API       使用程序集“ DatingApp.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.ModelValidator.ValidateNonNullPrimaryKeys(IModel   模型)          在Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel   模型)          在Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel   模型)          在Microsoft.EntityFrameworkCore.Internal.SqliteModelValidator.Validate(IModel   模型)          在Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext   上下文,IConventionSetBuilder ConventionSetBuilder,IModelValidator   验证器)          在Microsoft.EntityFrameworkCore.Infrastructure.ModelSource。<> c__DisplayClass5_0.b__1()          在System.Lazy 1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy 1.ExecutionAndPublication(LazyHelper执行AndPublication,布尔值useDefaultConstructor)处          在System.Lazy 1.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参数)          在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite   scopedCallSite,ServiceProviderEngineScope范围)          在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.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参数)          在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite   scopedCallSite,ServiceProviderEngineScope范围)          在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) 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](IInfrastructure 1 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   名称,字符串       outputDir,字符串contextType)          在Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String   名称,字符串outputDir,字符串contextType)          在Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration。<> c__DisplayClass0_1。<。ctor> b__0()          在Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase。<> c__DisplayClass3_0`1.b__0()          在Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(操作   行动)       实体类型“值”要求定义主键。

0 个答案:

没有答案