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*
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.
<connectionStrings>
section of yourapp.config
? – Chris Pickford(localdb)
usually refers to SQL Server LocalDB, which is a file based SQL database (like SqLite). Try changing that toData Source=localhost\mssqllocaldb
. – CodingGorilla<add name="ConnectionStringName" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True"/>
Please check yourapp.config
just to be sure. – Gareth van der Berg