I have created a database for use with a NuGet Gallery implementation. I can see the database in sql manager 2012 and I can access it from a test program I wrote, using my connection string. However, when I try to run the Update-Database command in the package manager console, to have EF set up the database, I keep getting the error: "The server was not found or was not accessible.".
Here's more detail:
PM> Update-Database -Verbose
Using StartUp project 'NuGetGallery.Operations'.
Using NuGet project 'NuGetGallery'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
System.Data.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. --->
System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. --->
System.Data.SqlClient.SqlException: 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 Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26
- Error Locating Server/Instance Specified) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
Here's my connection string in the NuGet Gallery MVC site:
<add name="Gallery.SqlServer" connectionString="Server=(localdb)\v11.0;Database=NuGetGallery11;User ID=testuser;Password=notmyrealpassword;Connect Timeout=60" providerName="System.Data.SqlClient"/>
And here's my test program. The connection strings are identical in both applications.
var sqlConnection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Gallery.SqlServer"].ConnectionString);
sqlConnection2.Open();
using (sqlConnection2) {
var sqlCmd = new SqlCommand("select * from Foo", sqlConnection2);
var foo = sqlCmd.ExecuteReader();
while (foo.Read()) {
int id = foo.GetInt32(0);
var name = foo.GetString(1);
var email = foo.GetString(2);
Console.WriteLine("ID:{0}, Name:{1}, Email:{2}", id, name, email);
}
}
Console.Read();
Any help would be greatly appreciated. Thanks!
My problem was solved in this other post here. You have to set the default project in the manager console AND set the startup project for the solution in order for the update command to find the connection string and also what Aydin said, but in this case that part was already set up for me.
Your problem is that EntityFramework doesn't know that your connection string is named Gallery.SqlServer...
Here's how you can setup entity framework from scratch...
Open VS with Administrative rights (just being cautious)
Create a new Console application
Open the package manager console
Type in: `PM> Install-Package EntityFramework
Open the App.Config file
Add the following
<connectionStrings>
<add name="Gallery.SqlServer" connectionString="Server=(localdb)\v11.0;Database=GalleryExample;" providerName="System.Data.SqlClient"/>
</connectionStrings>
Create a new class called Foo
public class Foo
{
public Foo()
{
this.Id = Guid.NewGuid()
.ToString();
}
public string Id { get; set; }
}
Create a new class called EfContext
public class EfContext : DbContext
{
public EfContext()
: base("Gallery.SqlServer")
{
}
public DbSet<Foo> Foos { get; set; }
}
Open up the package manager console again
PM> Enable-Migrations
PM> Add-Migration InitialMigration
PM> Update-Database
Enjoy your new db....
Related
Problem I'm dealing with, is weird error :
SqlException: 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 Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)
it happens whenever any method with db is called, like:
foo()
{
return _dbContext.data.ToList();
}
File db was created automatically based on code first approach and connection string:
<add name="Context"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\RestApi.Services.Context.mdf;Initial Catalog=RestApi.Services.Context;Integrated Security=True"
providerName="System.Data.SqlClient" />
I can connect with no errors to that file by VS server explorer.
On same PC I've runned several others apps with file db without any errors.
When I watch "Context" var in debbuger it seems connected to proper DB, but have error on workspaceID.
Now I'm stuck and don't have any idea how to fix it. :(
UnityConfig:
public static void RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType<Context, Context>(new PerThreadLifetimeManager());
container.RegisterType<IXService, XService>();
DependencyResolver.SetResolver(new Unity.Mvc5.UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
}
Context class:
public class Context : DbContext
{
public Context() : base("name=Context")
{
}
public DbSet<X> Xs{ get; set; }
public DbSet<Z> Zs{ get; set; }
public DbSet<Y> Ys{ get; set; }
}
EDIT
File Db was not the problem, I've tried with normal db connection string, and errors still occur.
I've tried many different solutions and no one works :(
now after change in UnityConfig:
public static void RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType<DbContext, Context>();
container.RegisterType<IXService, XService>();
DependencyResolver.SetResolver(new Unity.Mvc5.UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
}
first db read:
InvalidOperationException: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
next ones:
NullReferenceException: Object reference not set to an instance of an object.
EDIT2
Docker support was causing problems ;/ I'll upload solution when I find one
make sure that connectionstring data source is valid server name. if server name is valid then follow this instruction, this may help you.
Open "SQL Server Configuration Manager"
Now Click on "SQL Server Network Configuration" and Click on "Protocols for Name"
Right Click on "TCP/IP" (make sure it is Enabled) Click on Properties
Now Select "IP Addresses" Tab -and- Go to the last entry "IP All"
Enter "TCP Port" 1433.
Now Restart "SQL Server .Name." using "services.msc" (winKey + r)
I have setup two configuration for migration one is for SQL server and another is for MySql. SQL Server migration is now not being used. Now my problem is when I execute Sql Server migration with Update-Database -ConfigurationTypeName InTouchEnterprise.Data.Repository.MySqlMigrations.Configuration -verbose. It gives me following error
Authentication to host 'localhost' for user 'test' using method 'mysql_native_password' failed with message: Access denied for user 'test'#'localhost' (using password: NO)
But If I run the project it gets successfully connected to the database and do all the operation with database correctly. Now I am clue less what could have been wrong.
According to the error message it says that I am not specifying the password but I have specified password in the web.config. below is my connection string.
<add name="IdentityDB" providerName="MySql.Data.MySqlClient"
connectionString="server=localhost;port=3306;database=rtd;uid=test;password=*******" />
Below is code for Configuration class:
internal sealed class Configuration : DbMigrationsConfiguration<InTouchEnterprise.Data.Repository.InTouchEnterpriseDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = #"MySqlMigrations";
//for mysql
SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
}
protected override void Seed(InTouchEnterprise.Data.Repository.InTouchEnterpriseDbContext context)
{
}
}
I don't know the exact issue but when I added persist security info in connection string in web.config to true it started working again. Here is my updated connection string.
<add name="IdentityDB" providerName="MySql.Data.MySqlClient"
connectionString="server=localhost;port=3306;database=rtd;uid=root;password=*****;persistsecurityinfo=True" />
I have set up a Code First using the following DbContext
public class MyDatabaseDbContext : DbContext
{
public MyDatabaseDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public MyDatabaseDbContext()
: base("MyDatabase")
{
}
public DbSet<MyTable> MyTables { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
I have also set up the connection string to look at the (Local) database
<connectionStrings>
<add name="MyDatabase"
connectionString="Server=(local);Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
Also set up the initializer in Global.asax
Database.SetInitializer<MyDatabaseDbContext>(new DropCreateDatabaseAlways<MyDatabaseDbContext>());
I then run the application and call the DbContext (in my case from the controller)
var dbContext = new MyDatabaseDbContext();
var myTableResults = dbContext.MyTables.ToList();
I get the follow error message
An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code
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 Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot get a local application data path. Most probably a user profile is not loaded. If LocalDB is executed under IIS, make sure that profile loading is enabled for the current user.
On Debugging and looking at the dbContext variable > Database > Connection > ConnectionString Property I see the following:
"Data Source=(localdb)\v12.0;AttachDbFilename=|DataDirectory|MyDatabase.mdf;Initial Catalog=MyDatabase;Integrated Security=True;MultipleActiveResultSets=True"
Questions
Why is it pointing to the (localDb)\v12.0 database and not my connection string?
Even so, Why is it not creating the database there anyway as this is on my dev machine?
Is there some kind of convention which I have forgotten about which I need to set.
Your connection string needs to be named MyDatabaseDb
OR
your context class needs to be named MyDatabaseContext.
Entity Framework's convention is for the context class to look for a connection string with the same name + Context. The Db in your class name is extraneous.
I have an MVC5 project with Individual user account authentication. I have make a test registered myself and everythings works. Then for test sake I've added a property to ApplicationUser class, now ti looks like this:
public class ApplicationUser : IdentityUser
{
public string NewPropery { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
Then I've opened the Package Manager Console in Visual Studio 2013 and run:
PM> Enable-Migrations
PM> Add-Migration "NewProperty"
PM> Update-Database
first two commands goes well but fail on the third command and this is the error:
System.Data.SqlClient.SqlException (0x80131904): 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 Server is configured to
allow remote connections. (provider: SQL Network Interfaces, error: 26
- Error Locating Server/Instance Specified)
The database is the usual LocalDb created by MVC template, I leave the connection string in the project as it was created:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-NyProject.Web-20160325120840.mdf;Initial Catalog=aspnet-MyProject.Web-20160325120840;Integrated Security=True"
providerName="System.Data.SqlClient" />
Where is the error?
UPDATE 1 - After Steve comment
I use to select the project in Package Manager Console, making the project a "Startup project" this will produce a different error There is already an object named 'AspNetRoles' in the database..
This is true. Should I remove pre-existent tables, and what about my data?
You are getting that error because you have not established a baseline initial migration so EF thinks all your objects need to be created. This is because it builds models based on the code and compares it to the snapshot stored in the last migration, so try this:
1) Comment out the new field.
2) Delete the existing migration.
3) Add a baseline migration: add-migration Initial -IgnoreChanges
4) update-database (now EF has a snapshot to compare changes to).
5) add-migration NewProperty
6) update-database
EF Under the Hood
I'm trying to use Code First with my local instance of Sql Server 2008 R2. I've create a user 'dev' and can log in and create databases using Sql Managment Studio. The problem is I keep getting an error message when trying to create a database using DbContext in EntityFramework. Here is the error message:
"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 Server is configured to allow remote connections. SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified"
The error message I checked my Sql Server and it does allow remote connections.
I've abstracted my system with the following code and get the same error:
namespace CodeFirstConsole
{
public class Program
{
static void Main(string[] args)
{
var db = new MyContext();
try { Console.WriteLine(db.Parents.Count()); }
catch (Exception) { throw; }
Console.Read();
}
}
internal class MyContext : DbContext
{
public DbSet<ParentObject> Parents { get; set; }
public DbSet<ChildObject> Children { get; set; }
public MyContext()
{
this.Database.Connection.ConnectionString =
"Data Source=.;Database=ConsoleTest;Initial Catalog=ConsoleTest;User ID=dev;Password=dev;";
}
}
internal class ParentObject
{
public int Id { get; set; }
public string PropertyOne { get; set; }
}
internal class ChildObject
{
public int Id { get; set; }
public bool PropertyOne { get; set; }
public string PropertyTwo { get; set; }
public virtual ParentObject Parent { get; set; }
}
internal class MyInitializer : DropCreateDatabaseAlways<MyContext>
{
protected override void Seed(MyContext context)
{
context.Parents.Add(new ParentObject() { PropertyOne = "hi" });
base.Seed(context);
}
}
}
I had the same error that drove me nuts for about a day. My situation was I had a large solution with a pre-existing start-up project and I was adding EF to the persistence project.
So the first step was to add the EF dependency. This created an app.config in my persistence project with the correct EF content. Then I went to Enable-Migrations and got the same error in this post. At this point I didn't think of copying the EF app.config settings to the app.config of the start-up project since I thought I'd have to play around with it before I would eventually run the app.
The problem was resolved when I changed the solution start-up project to the persistence project so I could get EF to find the correct app.config. Or I could have copied the EntityFramwework related section to the app.config of the start-up project.
Had the same error message developing on local, but it worked fine yesterday.
Turns out the wrong project in the solution was set as the StartUp Project.
So if you are also getting this message after an update-database command in the Package Manager Console, be sure to check if the correct StartUp Project is set.
For example the Web project, and not one of the helper projects.
Visual studio seems to have the habit of setting other projects as the StartUp by itself sometimes...
Try having a look here it explains a lot of the causes, since you indicated in the comments that you did explicitly specify server name and the code runs also on the same machine as sql server since from what I see the datasource just has a dot, indicating that its the same machine as the c# code program running on.
http://blogs.msdn.com/b/sql_protocols/archive/2007/05/13/sql-network-interfaces-error-26-error-locating-server-instance-specified.aspx
Had to add the EntityFramework dependency also to the startup project.
Install-Package EntityFramework
And also had to define connectionStrings to my main project App.config/Web.config.
<connectionStrings>
<add name="Database" providerName="System.Data.SqlClient" connectionString="foo.bar" />
</connectionStrings>
Here was a solution for me
Traditional SqlClient can find server instance but EF can't
In short:
Database.SetInitializer<MyContext>(
new MigrateDatabaseToLatestVersion<MyContext, Migrations.Configuration>(
useSuppliedContext: true));
Main part here is useSuppliedContext: true
I had the same problem and spent a whole day on it. Finally found #Christian's answer and now I find a much better way!
Put ConnectionString in the startup project. So you don't need to switch every time you change an entity.