不使用 ASP.Net Core 2 中的迁移命令 Update-Database 创建数据库

2024-03-02

我使用 WebAPI 创建了新的 ASP.Net core 项目。使用下面的链接。

jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login

我必须手动使用 add-migration update-database 。

这里我再补充一件事,就是我不知道如何在VS Code中调试app。在 VS Code 中创建项目后,我在 Visual Studio 2017 中打开我的项目。

当我要运行更新命令时Update-Database在包管理器控制台中。我还遇到以下错误,据我了解,上述命令是用于创建数据库并在其中添加迁移表。 (如我错了请纠正我)。

 fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
  Failed executing DbCommand(3ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
  CREATE TABLE[AspNetRoles] (

     [Id] nvarchar(450) NOT NULL,
     [ConcurrencyStamp] nvarchar(max) NULL,
      [Name] nvarchar(256) NULL,
      [NormalizedName] nvarchar(256) NULL,
      CONSTRAINT[PK_AspNetRoles] PRIMARY KEY([Id])
  );
 System.Data.SqlClient.SqlException(0x80131904): There is already an object named 'AspNetRoles' in the database.

 at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)

 at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action 1 wrapCloseInAction)

 at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)

 at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)

 at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)

 at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)

 at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

 at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues)

 ClientConnectionId:56b94f04-73ff-4391-87fc-36a6c256c650

 Error Number:2714,State:6,Class:16

 System.Data.SqlClient.SqlException(0x80131904): There is already an object named 'AspNetRoles' in the database.

 at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)

 at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)

 at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)

 at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)

 at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)

 at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)

 at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

 at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues)

 at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)

 at      Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)


 at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable1 migrationCommands, IRelationalConnection connection)

 at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)

 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)

 ClientConnectionId:56b94f04-73ff-4391-87fc-36a6c256c650

 Error Number:2714, State:6, Class:16

 There is already an object named 'AspNetRoles' in the database.`

我还在这里分享了一些我的代码并将我的应用程序上传到github https://github.com/AhmerAli/ASP.Net-Core-2-webapi-Application

程序.cs

namespace server
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
             WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();

    }
}

启动.cs

public class Startup
{
    private const string SecretKey = "iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"; // todo: get this from somewhere secure
    private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

    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)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                b => b.MigrationsAssembly("server")));

        services.AddSingleton<IJwtFactory, JwtFactory>();

        // Register the ConfigurationBuilder instance of FacebookAuthSettings
        services.Configure<FacebookAuthSettings>(Configuration.GetSection(nameof(FacebookAuthSettings)));

        services.TryAddTransient<IHttpContextAccessor, HttpContextAccessor>();

        // jwt wire up
        // Get options from app settings
        var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

        // Configure JwtIssuerOptions
        services.Configure<JwtIssuerOptions>(options =>
        {
            options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
            options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
            options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
        });

        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

            ValidateAudience = true,
            ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

            ValidateIssuerSigningKey = true,
            IssuerSigningKey = _signingKey,

            RequireExpirationTime = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

        }).AddJwtBearer(configureOptions =>
        {
            configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
            configureOptions.TokenValidationParameters = tokenValidationParameters;
            configureOptions.SaveToken = true;
        });

        // api user claim policy
        services.AddAuthorization(options =>
        {
            options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
        });

        // add identity
        var builder = services.AddIdentityCore<EmployeeProfile>(o =>
        {
            // configure identity options
            o.Password.RequireDigit = false;
            o.Password.RequireLowercase = false;
            o.Password.RequireUppercase = false;
            o.Password.RequireNonAlphanumeric = false;
            o.Password.RequiredLength = 6;
        });
        builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
        builder.AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

        services.AddAutoMapper();
        services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
    }

    // 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();
        }

        app.UseExceptionHandler(
            builder =>
            {
                builder.Run(
                    async context =>
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

                            var error = context.Features.Get<IExceptionHandlerFeature>();
                            if (error != null)
                            {
                                context.Response.AddApplicationError(error.Error.Message);
                                await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
                            }
                        });
            });

        app.UseAuthentication();
        app.UseDefaultFiles();
        app.UseStaticFiles();
        app.UseMvc();
    }
}

应用程序DbContext.cs

public class ApplicationDbContext : IdentityDbContext<EmployeeProfile>
{
    public ApplicationDbContext(DbContextOptions options)
        : base(options)
    {
    }

    public DbSet<EmployeeProfile> EmployeeProfiles { get; set; }
}

我的问题是如何使用迁移更新命令创建数据库以及我的代码出了什么问题。


我找到了我的问题的答案。

我只需要更改以下两个文件中的 DefaultConnection:

appsettings.json and appsettings.Development.json

Before

"ConnectionStrings": {
"DefaultConnection": "Server=(LocalDb)\\MSSQLLocalDB;Database=webapi;Trusted_Connection=True;MultipleActiveResultSets=true"
}

After

"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=WebApiEfCore;Trusted_Connection=True;"
}

然后运行以下查询。

dotnet ef migrations add initial
dotnet ef database update

以及它是如何运作的。这是一个经过验证的快照。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

不使用 ASP.Net Core 2 中的迁移命令 Update-Database 创建数据库 的相关文章

  • 到底什么是“位填充”或“填充位”?

    我只是在互联网上找不到任何关于 位填充 真正含义的详细解释 并且在 Stack Overflow 上也没有找到与位填充相关的线程的任何答案 我还搜索了 ISO 9899 1990 其中提到了 位填充 但没有根据我的需要进行解释 我在网上找到
  • 更改 Visual Studio 2015 扩展中项目内的文件 ProjectItem 的内容?

    如何更改文件的内容 ProjectItem在给定的范围内Project 我想用字符串替换它的所有内容 这个问题有解决办法吗 我想做一些改变ProjectItem CS 文件 通过使用 VSIX 包 以及我现在看到的唯一一种执行此操作的方法
  • 在静态断言和运行时错误之间自动选择

    我有一个执行除法并检查对齐的宏 define BYTES TO WORDS x CHECK ALIGNMENT x 2 x 2 我想实施CHECK ALIGNMENT作为一个总是返回 1 的宏 并且如果满足以下条件则触发错误x不除以 2 宏
  • 如何使用 saxon 将文档类型参数传递给 xslt?

    对于发送原子数据类型将使用类似 transformer SetParameter new QName customXml new XdmAtomicValue true 如何将 XML Node 作为参数从 C 传递给 XSLT 你能帮我么
  • 实体框架 5 不清除导航属性

    我在 Entity Framework 5 中遇到了这个奇怪的问题 我在其中一个实体中有一个导航属性 我想将其设置为null 但由于某种原因 该属性只有在我第二次调用该属性时才会被清除 using var db new Entities v
  • 模拟 EF core dbcontext 和 dbset

    我正在使用 ASP NET Core 2 2 EF Core 和 MOQ 当我运行测试时 我收到此错误 消息 System NotSupportedException 非虚拟 可在 VB 中重写 成员上的设置无效 x gt x Movies
  • string.empty 和 string[0] == '\0' 之间的区别

    假设我们有一个字符串 std string str some value is assigned 有什么区别str empty and str 0 0 C 11 及更高版本 string variable 0 如果字符串为空 则需要返回空字
  • DLL 需要访问其应用程序的符号

    在 C 中 DLL 是否可以访问加载它的应用程序的某些符号 我有一个加载插件 dll 的应用程序 这些插件需要访问该应用程序的某些API 是否可以在不创建共享此 API 的新 DLL 的情况下实现此目的 函数指针结构适合这种情况吗 示例 主
  • C# 列表框 ObservableCollection

    我正在尝试使用 ListBox DataSource ObservableCollection 但是我不知道如何在 OC 更新时让列表框自动更新 我可以在 OC 上挂接 CollectionChanged 事件 但是我需要对列表框执行什么操
  • 如何在单独的类库中管理客户端上下文对象?

    我正在尝试创建一个库 类库 对于共享点 它将拥有所有共享点 dll 来与共享点服务器交互上传文件 文档并创建文档库和文档集 现在这个库可以被使用客户端 例如 Web 应用程序 asp net webform 或 mvc 或控制台应用程序或
  • tcmalloc/jemalloc 和内存池之间有什么区别(以及选择的理由)?

    tcmalloc jemalloc是改进的内存分配器 还引入了内存池以更好地分配内存 那么它们之间有什么区别以及在我的应用中如何选择它们呢 这取决于您的程序的要求 如果您的程序有更多的动态内存分配 那么您 需要从可用的分配器中选择一个内存分
  • 当应用程序未聚焦时监听按键

    我有一个应用程序 C 4 0 WPF 它是隐藏的 可以通过单击系统托盘图标或我创建的其他框架 停靠在左侧和最上面的小框架 来显示 My customer wants to add a new way to display the appli
  • XPath 选择具有特定属性值的元素?

    我在使用 XPath 选择节点时遇到问题 我将展示一个示例 由于实际数据量很大 xml 文件被缩短了 这是 XML 的子集
  • 如何定义 Swagger UI 参数的默认值?

    我已将 Swagger Swashbuckle 集成到 NET Core 2 2 API 项目中 一切都很好 我的要求纯粹是为了方便 考虑以下 API 方法 public Model SomeEstimate SomeRequest req
  • System.Drawing.Icon 构造函数抛出“操作成功完成”异常

    在 Windows XP 计算机上 以下代码抛出 System ComponentModel Win32Exception 并显示消息 操作成功完成 System Drawing Icon icon new System Drawing I
  • STL 向量、迭代器和插入 (C++)

    我有一个将向量的迭代器传递到的方法 在这个方法中 我想向向量中添加一些元素 但我不确定当只有迭代器时这是否可行 void GUIComponentText AddAttributes vector
  • 可选参数代码在 .NET 3.5 中编译。为什么?

    这段代码在 VS 2010 的框架 3 5 项目中编译正常 我三次检查过 public LoggingClient string uri net msmq localhost logging 为什么 我在 C 4 规范中没有看到任何内容 文
  • 任何浮点密集型代码是否会在任何基于 x86 的架构中产生位精确的结果?

    我想知道使用浮点运算的 C 或 C 代码是否会在任何基于 x86 的体系结构中产生位精确的结果 无论代码的复杂性如何 据我所知 自 Intel 8087 以来的任何 x86 架构都使用准备处理 IEEE 754 浮点数的 FPU 单元 并且
  • 用于高级搜索/过滤的.Net Web API URL 约定

    我对 Microsoft 的 REST 和 WebAPI 比较陌生 我们正在实现一个中心 REST 服务 它将容纳多种类型的对象获取和设置 作为该项目的领导者 我的任务是提出我们正在使用的正确的 Uri 设计 我想知道关于战争什么想法更好
  • 从哪里开始阅读 SQLite 源代码? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我想了解sqlite是如何实现的 并且 想阅读源代码 我已经下载了源代码 我应该开始查看代码的哪一部分 SQLite文档页 http

随机推荐

  • Asp.Net 中动态添加的控件

    我正在尝试了解 asp net 我有一个长期的 php 开发人员背景 但我现在面临着学习 asp net 的任务 并且我在这方面遇到了一些麻烦 这很可能是因为我试图迫使框架去做一些它不适合的事情 所以我想学习如何 以正确的方式 做到这一点
  • 如何在 h:selectOneMenu 中的值更改时执行转换?

    通常我会做如下的事情 单击按钮执行转换
  • 全局名称“re”未定义

    我是 python 新手 正在研究 mincemeat 的地图减少问题 运行 mincemeat 脚本时出现以下错误 python mincemeat py p changeme localhost error uncaptured pyt
  • Javascript 和 Howler.js - 如何选择随机声音?

    我对 javascript 相当陌生 并尝试在 mousemove 上播放随机选择的声音 我无法上班 希望得到帮助 我使用 howler min js 来控制声音 因此不会等到声音播放结束才播放下一个声音 这是代码 var soundObj
  • 在 Swift 中生成字符串的自定义长度哈希值

    是否有可能以某种方式将长度为 n 的给定字符串 哈希 为任意长度 m 的哈希值 我想实现如下目标 let s1
  • 在Python中输入一个文本文件并写入多个输出文件

    大家好 我正在输入 filename txt 并生成多个输出文件 filename1 txt filename2 txt 和 filename3 txt 更具体地说 这是 filename txt 中的输入数据 Time ms Channe
  • rvm 无法再在 Mac OS X Mountain Lion 上安装 1.8.7-p352

    我将 rvm 升级到 1 15 8 然后在 zsh 出现一些问题后又降回 1 15 7 降级后 我的 Ruby 1 9 版本恢复正常 但 1 8 7 无法再次安装 出现两个错误 Error running patch F 25 p1 N f
  • Fabric JS 通过 ID 以编程方式选择对象

    在 Fabric JS 中 我需要通过给定的对象名称 ID Circle 来选择对象 var onCircle function canvas add new fabric Circle id Circle radius 30 fill f
  • 使用分数的模算术

    我陷入了这个使用整数和分数模 10 相乘的密码学问题 这是等式 7 4 11 mod 10 我知道我应该将其转换为整数 因为 mod 运算符不适用于分数 但我无法弄清楚这一点 明显地 7 4 11 28 11 但我无法得到分数的 mod 1
  • JQuery.validate - 仅关于模糊的一条规则;其余的应该正常吧?

    我已经用小提琴来展示我试图为我的用户 ID 字段执行的简单验证 使其成为必需 尽可能积极地验证 设置最小长度 尽可能积极地验证 设置最大长度 尽可能积极地验证 运行 AJAX 调用以确保用户 ID 不存在 我只想在模糊时运行它 我没有使用
  • GDB 中断命令不会在命令文件中执行

    我有一个调试脚本 它执行以下操作 设置两个断点 让我们称呼他们吧start and end断点 启动后 脚本将继续执行 直到start命中断点 once start命中断点 我执行单步执行 直到end命中断点 这是我的命令文件 end br
  • vue.js 中的过滤器和方法有什么区别?

    我想将时间戳转换为北京时间 我应该使用过滤器还是方法来实现此功能 有什么区别 比如性能上的区别 仅当基础时间戳更改时 显示的北京时间才需要更改 方法因此应该not be used https v2 vuejs org v2 guide co
  • 如何仅显示绘图中特定曲线子集的图例?

    t 0 0 01 2 pi s sin t c cos t m sin t hold on plot t s r plot t c b plot t m g hold off legend cosine 我的绘图中有几条曲线 我只想显示其中
  • 使用 LINQ 对对象列表进行分组

    我有一个对象 public class Customer public int ID get set public string Name get set public int GroupID get set 我返回一个可能如下所示的列表
  • docker-compose 中不同 docker 服务之间的通信

    我刚刚开始使用 docker compose 目前正在努力解决不同服务之间的通信问题 我有2个服务 alice and bob 我希望它们能够互相发送 http 请求 据我了解 服务应该能够通过使用服务名作为主机名来相互访问 很遗憾 ali
  • jQuery 将类添加到单选框未删除

    我使用 jQuery 将一个类添加到单选框 如果它被选中 这工作正常 但在选择另一个单选框时它不会删除该类 我缺少什么 jQuery checkbox radio change function if this is checked thi
  • 在 Visual Studio 中调试期间评估表达式

    我习惯了 Jetbrains IDEA 和 Java 但现在我有一个 NET C 项目并使用 Visual Studio 2017 社区 如果我在 IDEA 中调试代码 当执行在断点处停止时 我始终可以使用 IDE 的 评估表达式 功能来运
  • 从给定的 x86 程序集编写 C 函数

    我正在尝试对这个神秘的函数进行逆向工程 该函数返回一个整数并接受一个结构节点作为参数 include mystery h int mystery struct e4 struct s 头文件是一个简单的结构体声明 struct my str
  • Qt 应用程序:模拟模态行为(启用/禁用用户输入)

    我目前正在开发一个应用程序 该应用程序启动显示附加对话框的单独进程 我试图实现的功能是模拟这些对话框的模式行为 更具体地说 我需要应用程序在对话框启动时停止处理所有输入 包括鼠标和键盘 并在对话框关闭时恢复 对话框保持在应用程序顶部并不是那
  • 不使用 ASP.Net Core 2 中的迁移命令 Update-Database 创建数据库

    我使用 WebAPI 创建了新的 ASP Net core 项目 使用下面的链接 jwt authentication with aspnet core 2 web api angular 5 net core identity and f