1 year ago

#362333

test-img

Datadump

DBContext connection to SQL Server Express throws exception using the added app.config, what is missing?

Without using .net core, I worked on an existing .net framework 4.8 Console project that's missing app.config, trying to replicate the tutorial on how to create a dbContext to SQL Server Express. So I've added an app.config manually by googling, setting the values as I see fit, but it seems something is still missed or I need to add something.

Below is my code so far that throws the error, I was hoping to see "TestDB" database in App_Data be created when I simply add a single row.

System.Data.Entity.Core.ProviderIncompatibleException: 'An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.'

Config file:

<configuration>
  <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>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
  </startup>
    <connectionStrings>
        <add name="TestDbContextConString"
             connectionString="Data Source=DESKTOP-OEQUB30\SQLEXPRESS; Initial Catalog=TestDB;
      Integrated Security=True;MultipleActiveResultSets=False" providerName="System.Data.SqlClient" />
    </connectionStrings>    
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>    

    

TestClass.cs

public class TestClass
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }    
}

public class TestDataDbContext : DbContext
{
    public TestDataDbContext() : base("TestDbContextConString")
    {
    }

    public DbSet<TestClass> TestClasses { get; set; }
}

Program.cs

public class Program
{
    static void Main(string[] args)
    {
        using(var context = new TestDataDbContext())
        {
            context.TestClasses.Add(new TestClass
            {
                Name = "John Smith",
                Age = 34
            });

            context.SaveChanges();  
        }
    }
}

SQL Server Express

.net

sql-server

entity-framework

dbcontext

0 Answers

Your Answer

Accepted video resources