2017-01-31 11 views
0

Я пытаюсь использовать идентификатор AspNetCore для нашего проекта, мы используем базу данных Postgresql.Первичный ключ идентификации .NETCORE

Я младший разработчик и сегодня моя задача состоит в том, что изменить первичный ключ идентификации для INT, я исследовал и нашел эту статью https://medium.com/@goodealsnow/asp-net-core-identity-3-0-6018fc151b4#.k602cypgb

, но это не помогает мне, так у меня есть некоторые ошибки.

это мой ApplicationDbContext.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 
using Microsoft.EntityFrameworkCore; 
using Identitytest.Models; 

namespace Identitytest.Data 
{ 
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int> 
    { 
     public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) 
      : base(options) 
     { 
     } 

     protected override void OnModelCreating(ModelBuilder builder) 
     { 

     } 
    } 
} 

Это мой startup.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using Microsoft.AspNetCore.Builder; 
using Microsoft.AspNetCore.Hosting; 
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 
using Microsoft.EntityFrameworkCore; 
using Microsoft.Extensions.Configuration; 
using Microsoft.Extensions.DependencyInjection; 
using Microsoft.Extensions.Logging; 
using Identitytest.Data; 
using Identitytest.Models; 
using Identitytest.Services; 

namespace Identitytest 
{ 
    public class Startup 
    { 
     public Startup(IHostingEnvironment env) 
     { 
      var builder = new ConfigurationBuilder() 
       .SetBasePath(env.ContentRootPath) 
       .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 
       .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); 

      if (env.IsDevelopment()) 
      { 
       // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 
       builder.AddUserSecrets(); 

       // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. 
       builder.AddApplicationInsightsSettings(developerMode: true); 
      } 

      builder.AddEnvironmentVariables(); 
      Configuration = builder.Build(); 
     } 

     public IConfigurationRoot Configuration { get; } 

     // This method gets called by the runtime. Use this method to add services to the container. 
     public void ConfigureServices(IServiceCollection services) 
     { 
      // Add framework services. 
      services.AddApplicationInsightsTelemetry(Configuration); 

      services.AddDbContext<ApplicationDbContext>(options => 
       options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"))); 

      services.AddIdentity<ApplicationUser, IdentityRole<int>>() 
       .AddEntityFrameworkStores<ApplicationDbContext,int>() 
       .AddDefaultTokenProviders(); 

      services.AddMvc(); 

      // Add application services. 
      services.AddTransient<IEmailSender, AuthMessageSender>(); 
      services.AddTransient<ISmsSender, AuthMessageSender>(); 
     } 

     // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
     { 
      loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
      loggerFactory.AddDebug(); 

      app.UseApplicationInsightsRequestTelemetry(); 

      if (env.IsDevelopment()) 
      { 
       app.UseDeveloperExceptionPage(); 
       app.UseDatabaseErrorPage(); 
       app.UseBrowserLink(); 
      } 
      else 
      { 
       app.UseExceptionHandler("/Home/Error"); 
      } 

      app.UseApplicationInsightsExceptionTelemetry(); 

      app.UseStaticFiles(); 
      app.UseIdentity(); 
      app.UseIdentity(); 

      // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715 

      app.UseMvc(routes => 
      { 
       routes.MapRoute(
        name: "default", 
        template: "{controller=Home}/{action=Index}/{id?}"); 
      }); 
     } 
    } 
} 

Это мой Program.cs

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Threading.Tasks; 
using Microsoft.AspNetCore.Hosting; 

namespace Identitytest 
{ 
    public class Program 
    { 
     public static void Main(string[] args) 
     { 
      var host = new WebHostBuilder() 
       .UseKestrel() 
       .UseContentRoot(Directory.GetCurrentDirectory()) 
       .UseIISIntegration() 
       .UseStartup<Startup>() 
       .Build(); 

      host.Run(); 
     } 
    } 
} 

Теперь, когда я пытаюсь Обновление базы данных У меня есть ошибка, подобная этому

PM> Update-Database 
System.InvalidOperationException: The entity type 'IdentityUserLogin<int>' requires a primary key to be defined. 
    at Microsoft.EntityFrameworkCore.Internal.ModelValidator.ShowError(String message) 
    at Microsoft.EntityFrameworkCore.Internal.ModelValidator.Validate(IModel model) 
    at Microsoft.EntityFrameworkCore.Internal.RelationalModelValidator.Validate(IModel model) 
    at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator) 
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) 
    at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() 
    at Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value() 
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) 
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) 
    at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServiceCollectionExtensions.<>c.<AddEntityFramework>b__0_13(IServiceProvider p) 
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) 
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) 
    at Microsoft.EntityFrameworkCore.Infrastructure.RelationalServiceCollectionExtensions.<>c.<AddRelational>b__0_8(IServiceProvider p) 
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider) 
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) 
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) 
    at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType) 
    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0() 
    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) 
The entity type 'IdentityUserLogin<int>' requires a primary key to be defined. 

Я не понимаю, что я могу сделать для этой проблемы? Мне нужно изменить свой основной ключ на INT, я сделал все, что делает этот парень на medium.com, но мой код не работает.

ответ

0

Судя по ней, вы можете сделали все правильно до сих пор, но вы не упомянули, что вы вошли в файл ApplicationContext.cs и изменил подпись:

public class ApplicationDbContext : 
       IdentityDbContext<ApplicationUser, IdentityRole<int>, int> 

Тогда вам нужно перейти в файл ApplicationUser.cs и изменить класс подпись:

public class ApplicationUser : IdentityUser<int> 
{ 
} 

Я получил ASP.Net сердечник Идентичность работать таким образом, я использовал это в качестве руководства: https://medium.com/@goodealsnow/asp-net-core-identity-3-0-6018fc151b4#.4qsikvln3

Не беспокойтесь, что это SQL Server, вы уже изменили свой провайдер на Npgsql и установили параметры UseNpgsql, и это все, что вам нужно сделать.

Дайте мне знать, если это поможет.

Смежные вопросы