EntityFraemwork - Enable-Migrations - "No connection string named 'ConnectionString' could be found in the application config file"

0

Witam,
czy ktoś może udzielić mi porady i pokazać co robię źlę. Projektuję właśnie aplikację "Zarządzanie produkcją" w .net MVC z wykorzystaniem Entity Fraemwork. Mam w katalogu głównym plik Web.confg, gdzie mam skonfigurowane połączenie z bazą SQL Server (albo przynajmniej mi się tak wydaje)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<entityFramework>

  <!-- To customize the asp.net core module uncomment and edit the following section. 
  For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
  <!--
  <system.webServer>
    <handlers>
      <remove name="aspNetCore"/>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
  </system.webServer>
  -->
	<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameters>
        <parameter value="v11.0" />
        </parameters>
    </defaultConnectionFactory>
        <providers>
        <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
    </entityFramework>
>
 <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
  </configSections>
  <connectionStrings>
    <add name="ZarzadzanieProdukcja" connectionString="Data Source=TOMEKLATOPOP\SQLEXPRESS;Initial Catalog=ZarzadzanieProdukcja;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
  </connectionStrings>

</configuration>

utorzyłem kalsy tworzące table i wydaje polecenie

PM> Enable-Migrations
Checking if the context targets an existing database...
System.InvalidOperationException: No connection string named 'ConnectionString' could be found in the application config file.
   at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
   at System.Data.Entity.Internal.LazyInternalConnection.get_Connection()
   at System.Data.Entity.Internal.LazyInternalContext.get_Connection()
   at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func`1 resolver)
   at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, Func`1 resolver)
   at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
   at System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
   at System.Data.Entity.Infrastructure.Design.Executor.CreateMigrationScaffolder(DbMigrationsConfiguration configuration)
   at System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInitialCreateInternal(DbConnectionInfo connectionInfo, String contextTypeName, String contextAssemblyName, String migrationsNamespace, Boolean auto, String migrationsDir)
   at System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInitialCreate.<>c__DisplayClass0_0.<.ctor>b__0()
   at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.<>c__DisplayClass4_0`1.<Execute>b__0()
   at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
No connection string named 'ConnectionString' could be found in the application config file.

czy ktoś może mi służyć radą?

0

Raczej nie projektujesz, ale to nie ważne.
Zmień

<add name="ZarzadzanieProdukcja"...

Na

<add name="ConnectionString"...

Więcej czytania, mniej pisania.

0
jacek.placek napisał(a):

Raczej nie projektujesz, ale to nie ważne.
Zmień
<add name="ZarzadzanieProdukcja"...

Na
<add name="ConnectionString"...

Więcej czytania, mniej pisania.

zorientowałem się wcześniej, też jest ten sam komunikat

<configSections>
		<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
		<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
	</configSections>
	<connectionStrings>
		<add name="ConnectionString" providerName="System.Data.SqlClient" connectionString="Server=TOMEKLAPTOPOP\SQLEXPRESS;Database=PRODUCTION_MANAGMENT;Trusted_Connection=True;MultipleActiveResultSets=true"/>
	</connectionStrings>

0
Tomasz M. Myszak napisał(a):
jacek.placek napisał(a):

Raczej nie projektujesz, ale to nie ważne.
Zmień
<add name="ZarzadzanieProdukcja"...

Na
<add name="ConnectionString"...

Więcej czytania, mniej pisania.

zorientowałem się wcześniej, też jest ten sam komunikat

<configSections>
		<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
		<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
	</configSections>
	<connectionStrings>
		<add name="ConnectionString" providerName="System.Data.SqlClient" connectionString="Server=TOMEKLAPTOPOP\SQLEXPRESS;Database=PRODUCTION_MANAGMENT;Trusted_Connection=True;MultipleActiveResultSets=true"/>
	</connectionStrings>

treść kalsy tworzącej bazę danych

  public class CalculatorContext : DbContext
    {
        public CalculatorContext()
            : base("name=ConnectionString") { }

        public DbSet<SearchHistory> SearchHistory { get; set; }
        public DbSet<Module> Module { get; set; }
        public DbSet<City> City { get; set; }
    }


    public class City
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public double TransportCost { get; set; }

        public double CostOfWorkingHour { get; set; }

        public virtual SearchHistory SearchHistory { get; set; }
    }


    public class Module
    {
        public int Id { get; set; }

        public string Code { get; set; }

        public string Name { get; set; }

        public double Price { get; set; }

        public double AssemblyTime { get; set; }

        public double Weight { get; set; }

        public string Description { get; set; }

        public virtual SearchHistory SearchHistory { get; set; }
    }


    public class SearchHistory
    {
        public int Id { get; set; }

        public int CityId { get; set; }

        public string ModuleName1 { get; set; }

        public string ModuleName2 { get; set; }

        public string ModuleName3 { get; set; }

        public string ModuleName4 { get; set; }

        public double ProductionCost { get; set; }
    }

1

Nie w tym projekcie uruchamiasz co ma connection string?
Ustaw na domyślny projekt z db Context.

0
jacek.placek napisał(a):

Nie w tym projekcie uruchamiasz co ma connection string?
Ustaw na domyślny projekt z db Context.

przyznam, że nie bardzo zrozumiałem Twoją odpowiedź. w pliki web.config mam umieszczony kod

<connectionString> </connectionStrings>

a klasa wg poradnika Entity powinna utworzyć bazę i tabele.

0

Jak masz więcej niż 1 projekt w solution to migracje dziają z projektem, który masz wybrany w Package Manager Console ale używa konfiguracji z projektu, który jest ustawiony jako StartUp
Project.

Wpisz ten connection string do web.config.

0
jacek.placek napisał(a):

Jak masz więcej niż 1 projekt w solution to migracje dziają z projektem, który masz wybrany w Package Manager Console ale używa konfiguracji z projektu, który jest ustawiony jako StartUp
Project.

Wpisz ten connection string do web.config.

tak mam wpisany, mam otwarty jeden projekt. Błąd był w metodize

public CalculatorContext(String connectionString)
            : base("name=ConnectionString") { }

nie było dodanego String connectionString

z czego komunikat się zmienił

na

PM> Enable-Migrations
Checking if the context targets an existing database...
The target context 'ProductionManagment.Models.CalculatorContext' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory.
PM> 

0

Nie, to nie to. Klasa CalculatorContext musi mieć publiczny bezparametrowy konstruktor i dziedziczyć po DbContext

public class  CalculatorContext :  DbContext
{

    public CalculatorContext()
            : base("name=ConnectionString") { }

   //...

}
0
jacek.placek napisał(a):

Nie, to nie to. Klasa CalculatorContext musi mieć publiczny bezparametrowy konstruktor i dziedziczyć po DbContext

public class  CalculatorContext :  DbContext
{

    public CalculatorContext()
            : base("name=ConnectionString") { }

   //...

}

ma i wtedy jest odpowiedź

System.InvalidOperationException: No connection string named 'ConnectionString' could be found in the application config file.
at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
at System.Data.Entity.Internal.LazyInternalConnection.get_Connection()
at System.Data.Entity.Internal.LazyInternalContext.get_Connection()
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func1 resolver) at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, Func1 resolver)
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
at System.Data.Entity.Infrastructure.Design.Executor.CreateMigrationScaffolder(DbMigrationsConfiguration configuration)
at System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInitialCreateInternal(DbConnectionInfo connectionInfo, String contextTypeName, String contextAssemblyName, String migrationsNamespace, Boolean auto, String migrationsDir)
at System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInitialCreate.<>c__DisplayClass0_0.<.ctor>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.<>c__DisplayClass4_0`1.<Execute>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
No connection string named 'ConnectionString' could be found in the application config file.

0

No to gdzieś masz jakiś bałagan. A jaka wersja .NET? .NET 6 czy .Net Framework?
Zrób nowy projekt od początku i zwróć uwagę na tym projektu i wersję frameworka.

0
jacek.placek napisał(a):

No to gdzieś masz jakiś bałagan. A jaka wersja .NET? .NET 6 czy .Net Framework?
Zrób nowy projekt od początku i zwróć uwagę na tym projektu i wersję frameworka.

na Stockowerflow przeczytałem, że to może być kłopot wersji VS w '22 nie bardzo chcie pracować poprawnie. Zalecają wer '19.

Zainstalowałem '19 i pojawia się f

filed to bulid

poniżej link do githuba, może jak ktoś zerknie to udzleli mi porady co robię źle... W Entity Framework to mój pierwszy projekt.

link

0
Tomasz M. Myszak napisał(a):
jacek.placek napisał(a):

No to gdzieś masz jakiś bałagan. A jaka wersja .NET? .NET 6 czy .Net Framework?
Zrób nowy projekt od początku i zwróć uwagę na tym projektu i wersję frameworka.

na Stockowerflow przeczytałem, że to może być kłopot wersji VS w '22 nie bardzo chcie pracować poprawnie. Zalecają wer '19.

Zainstalowałem '19 i pojawia się f

filed to bulid

poniżej link do githuba, może jak ktoś zerknie to udzleli mi porady co robię źle... W Entity Framework to mój pierwszy projekt.

link

zmieniłem na public

0

Wróć do VS 2022.
Connection string powinienes wpisac w appsettings.json

0

AFAIR w Entity Framework Core (a tego używasz) migracje są włączone automatycznie i nie musisz robić Enable-Migrations, wystarczy dodać pierwszą migrację przez Add-Migration. https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=vs

(ale tak, connectionstring powinien być w appsettings.json, zapomnij o web.config, to jest Core)

0
Ktos napisał(a):

AFAIR w Entity Framework Core (a tego używasz) migracje są włączone automatycznie i nie musisz robić Enable-Migrations, wystarczy dodać pierwszą migrację przez Add-Migration. https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=vs

(ale tak, connectionstring powinien być w appsettings.json, zapomnij o web.config, to jest Core)

zgadza się, problemem było jak to kolega stwierdził na początku - więcej czytania, mniej pisania....

kod się skompilował, utworzyłem trzy strony w nowym folderze Pages i nie wyświetlają się.

0

Jak poprawnie używać EF Core i migracji:

  1. Tworzymy pustą bazę danych w SSMS
  2. Tworzymy model bazy danych:
public class Person
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}
public class ApplicationDbContext : DbContext
    {
        public DbSet<Person> Persons { get; set; } //Jakaś klasa
        
        public ApplicationDbContext()
        {

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

        }
    }
  1. Dodajemy ConnectionString do appSettings.json
"ConnectionStrings": {
    "LocalDB": "Server=localhost;Database=MyDB;Trusted_Connection=true"
  }
  1. Edytujemy plik startup.cs
public void ConfigureServices(IServiceCollection services)
{
            services.AddDbContext<ApplicationDbContext>(options =>
               options.UseSqlServer(
                   Configuration.GetConnectionString("LocalDB")));
            //...
  1. W konsoli pakietów NuGet wykonujemy polecenie add-migration initial (initial to dowolna nazwa migracji, musi być unikalna), a następnie update-database
  2. W serwisie lub kontrolerze wstrzykujemy kontekst bazy danych
public class PersonsService : IPersonsService
    {
        private readonly ApplicationDbContext _dbContext;
        
        public PersonsService(
            ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<Person[]> GetAll()
        {
            return await _dbContext.Persons
                .ToArrayAsync();
        }
    }

Jeżeli potrzebujesz bazy danych z modelem Identity to kod nieznacznie się różni

1 użytkowników online, w tym zalogowanych: 0, gości: 1