【问题标题】:Can't insert data into my database无法将数据插入我的数据库
【发布时间】:2017-08-01 23:31:02
【问题描述】:

我正在学习 ASP.NET Core 和 Entity 框架的教程,但我无法将数据插入到我的数据库中。我发现每当我评论该行时:

            DbInitializer.Initialize(context);

应用程序有效。

这一行在 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.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ContosoUniversity.Data;
using Microsoft.EntityFrameworkCore;


namespace ContosoUniversity
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .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.AddDbContext<SchoolContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddMvc();
        }

        // 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, SchoolContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

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

            app.UseStaticFiles();

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

这是我在启动网络应用程序时收到的错误消息

An error occurred while starting the application.

ArgumentException: Keyword not supported: '"server'.
System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary<string, string> parsetable, string connectionString, bool buildChain, Dictionary<string, string> synonyms)

ArgumentException: Keyword not supported: '"server'.
System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary<string, string> parsetable, string connectionString, bool buildChain, Dictionary<string, string> synonyms)
System.Data.Common.DbConnectionOptions..ctor(string connectionString, Dictionary<string, string> synonyms)
System.Data.SqlClient.SqlConnectionString..ctor(string connectionString)
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(string connectionString, DbConnectionOptions previous)
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, ref DbConnectionOptions userConnectionOptions)
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
System.Data.SqlClient.SqlConnection.set_ConnectionString(string value)
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection.CreateDbConnection()
Microsoft.EntityFrameworkCore.Internal.LazyRef.get_Value()
Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open()
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerDatabaseCreator+<>c__DisplayClass11_0.<Exists>b__0(DateTime giveUp)
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute<TState, TResult>(Func<TState, TResult> operation, Func<TState, ExecutionResult<TResult>> verifySucceeded, TState state)
Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute<TState, TResult>(IExecutionStrategy strategy, Func<TState, TResult> operation, TState state)
Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated()
ContosoUniversity.Data.DbInitializer.Initialize(SchoolContext context) in DbInitializer.cs
-
namespace ContosoUniversity.Data
{
    public static class DbInitializer
    {
        public static void Initialize(SchoolContext context)
        {
            context.Database.EnsureCreated();
            // Look for any students.
            if (context.Students.Any())
            {
                return; // DB has been seeded
            }
            var students = new Student[]
ContosoUniversity.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SchoolContext context) in Startup.cs
-
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            DbInitializer.Initialize(context);
        }
    }
}
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

Show raw exception details
System.ArgumentException: Keyword not supported: '"server'.
   at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms)
   at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
   at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
   at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
   at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
   at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
   at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection.CreateDbConnection()
   at Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open()
   at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass11_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](Func`2 operation, Func`2 verifySucceeded, TState state)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, Func`2 operation, TState state)
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated()
   at ContosoUniversity.Data.DbInitializer.Initialize(SchoolContext context) in C:\Users\iderlich\OneDrive\Documentos.Kerberos\Practica MVC\VS2017 PC Talca\ContosoUniversity\ContosoUniversity\Data\DbInitializer.cs:line 10
   at ContosoUniversity.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SchoolContext context) in C:\Users\iderlich\OneDrive\Documentos.Kerberos\Practica MVC\VS2017 PC Talca\ContosoUniversity\ContosoUniversity\Startup.cs:line 62
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
.NET Core X64 v4.1.1.0    |   Microsoft.AspNetCore.Hosting version 1.1.2    |    Microsoft Windows 6.1.7601 S    |   Need help?

【问题讨论】:

  • 您正在配置路由 inside db 初始化程序?这不合适。
  • 您使用的是什么类型的数据库,您的连接字符串是什么?一个简单的搜索表明这是与连接字符串相关的......
  • 您是否在项目中使用了 EDMX 文件? stackoverflow.com/questions/6646833/…
  • 这是我的连接字符串 "\"Server=(localdb)\\\\mssqllocaldb;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true\""
  • 我没有使用 EDMX 文件

标签: asp.net-mvc entity-framework


【解决方案1】:

您的连接字符串错误。 Server 应该是 Data Source

同时删除连接字符串中的引号。

【讨论】:

  • 根据错误ArgumentException: Keyword not supported: '"server'. 转义引号的方式似乎也存在问题,但在没有看到实际配置条目的情况下很难用给出的 sn-p 进行验证。
  • 解决了!这是我的连接字符串的问题。感谢你们!这是正确的连接字符串:“Server=(localdb)\\mssqllocaldb;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true” 我使用的连接字符串是 OP 评论中列出的那个
猜你喜欢
  • 2013-03-02
  • 1970-01-01
  • 1970-01-01
  • 2019-01-07
  • 2012-08-05
  • 2017-03-17
  • 2012-04-13
相关资源
最近更新 更多