-2

I'm taking a tutorial in ASP.NET Core and Entity framework and I can't insert data into my database. I've found that whenever I comment the line:

            DbInitializer.Initialize(context);

The Aplication works.

This line is in the Startup.cs file

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

This is the error message I get when I launch the web app

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?
Ivanz
  • 15
  • 1
  • 5
  • You are configuring routes *inside* the db initializer? That's out of place. –  Aug 01 '17 at 15:01
  • 3
    What kind of database are you using, and what's your connection string? A simple search reveals this is connection string related... –  Aug 01 '17 at 15:01
  • Are you using an EDMX file in your project? https://stackoverflow.com/questions/6646833/keyword-not-supported-server –  Aug 01 '17 at 15:04
  • This is my connection string "\"Server=(localdb)\\\\mssqllocaldb;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true\"" – Ivanz Aug 01 '17 at 15:08
  • I'm not using EDMX files – Ivanz Aug 01 '17 at 15:09
  • " routes inside the db initializer" What do you mean? – Ivanz Aug 01 '17 at 15:10
  • Not everyone keeps reading the comment section they posted on. If you want to ask a specific commentator a question you need to address them by typing their name using the `@` sign as a prefix. Example: `@Ivanz`. – Igor Aug 01 '17 at 15:17
  • @Ivanz your `DbInitializer` is supposed to *initialize the database*. You are configuring your MVC routes with `app.UseMvc(...)` inside the db initializer. It doesn't belong there. –  Aug 01 '17 at 15:23
  • Solved! It was a problem with my connection string. Thank you guys! This is the correct connection string: "Server=(localdb)\\mssqllocaldb;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true" The connection string I was using was the one listed in my previous comment. – Ivanz Aug 02 '17 at 18:56
  • Why are people giving me negative points? What am I doing wrong? – Ivanz Aug 02 '17 at 20:00

1 Answers1

2

Your connection string is bad. Server should be Data Source.

Also remove the quotes from the connection string.

  • Also looks like there is a problem with the way quotes are escaped based on error `ArgumentException: Keyword not supported: '"server'.` but difficult to verify with the snippet given without seeing the actual config entry. – AaronLS Aug 01 '17 at 15:28
  • Solved! It was a problem with my connection string. Thank you guys! This is the correct connection string: "Server=(localdb)\\mssqllocaldb;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true" The connection string I was using was the one listed in a comment on the OP – Ivanz Aug 02 '17 at 18:58