0
votes

I am new in Entity framework. I have a simple project using code-first approach.

This is codes:

 public class Student
    {
        public Student()
        {

        }

        [Key]
        public int id { get; set; }
        public string StudentName { get; set; }
    }

   

    public class SchoolContext:DbContext
    {
        public SchoolContext() : base()
        {
            Console.WriteLine(Database.Connection.ConnectionString);

        }

        public DbSet<Student> Students { get; set; }
    }

 static void Main(string[] args)
        {
            Student aa = new Student();
            aa.id=1 ;
            aa.StudentName = "eeee";
            using (var scContext = new SchoolContext())
            {
                scContext.Students.Add(aa);
                scContext.SaveChanges();
            }

            Console.Write("success");
        }

The connection string automatic create by Entity framework:

Data Source=(localdb)\mssqllocaldb;Initial Catalog=EFExample.Model.SchoolContext;Integrated Security=True;MultipleActiveResultSets=True

I installed sqlserver 2012 express, with 2 instances:

NT Service\MSSQLSERVER

NT Service\MSSQL$SQLEXPRESS

When i ran the program, i get an error :

*An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll

Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL* 

enter image description here

App.config

<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.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

Please help me what is wrong? Thank in advance.

3
Please could you post the <connectionStrings> section of your app.config?Chris Pickford
(localdb) usually refers to SQL Server LocalDB, which is a file based SQL database (like SqLite). Try changing that to Data Source=localhost\mssqllocaldb.CodingGorilla
@ Chris Pickford: i don't use connectionstring in app.config. I think EF will automatic create a connection string.nguyenmy
For SQLExpress instances I usually use this format: <add name="ConnectionStringName" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True"/> Please check your app.config just to be sure.Gareth van der Berg
Though it seems to be related with connStr as others said, could you also add Inner exception, just in case it might give us a clue. Also, your casing is inconsistent. Some variables are camelCase and some are PascalCase. Better stick to either, preferably camelCase as it's considered to be standard.uTeisT

3 Answers

1
votes

I'd suggest explicitly adding your own connectionstring in the app.config

`<connectionStrings>
    <add connectionString="Data Source=.\SQL_INSTANCE_NAME;Initial Catalog=DBName;Connection Timeout=60;Integrated Security=True;MultipleActiveResultSets=False" name="DbConnectionString" providerName="System.Data.SqlClient" />
</connectionStrings>`
0
votes

i ran into similar troubles, it seemed first to the sql server 2016 a setup problem, than some missing connection string in the web.config file. for the code first in asp.net mvc one line made it:

public OdeToFoodDb() : base("name=DefaultConnection") {

0
votes

i ran into similar troubles, it seemed first to the sql server 2016 a setup problem, than some missing connection string in the web.config file. for the code first in asp.net mvc one line made it:

e.g. my Model class is BeispielDb derived from DbContext thereafter the 'ctor' has mandatory to invoke the base 'ctor' with the db connection string:

public BeispielDb() : base("name=DefaultConnection")

the constructor has fed the DbContext(base class) constructor with the DefaultConnection string from the web.config.

Have a nice day and keep well,

Salomon MOYAL-BLOCH