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.
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 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
Background
I'm working on a project which contains both legacy code and Entity Framework code. I was advised to use a specific dataservice method to operate on a record from the database. The record was retrieved via Entity Framework, and I passed the PK into the dataservice function to perform the operation.
Preconditions for success and failure
If the network was up, both DB calls (entity and SQL) would succeed. If the network went down, then came back up and this code was executed, then it would retrieve the locked records with entity framework but then fail with the SqlException below.
This got me thinking, what is going on here that might cause the SqlConnection to fail despite EF being able to make the connection.
Code Samples
A code sample follows:
public void HandleNetworkBecomesAvailable() {
_entityFrameworkDataService.ReleaseRecords();
}
EntityFrameworkDataService.cs
public void ReleaseRecords()
{
using (var context = new Entities()) // using EntityConnection
{
var records = context.Records.Where(
record => record.IsLocked).ToList();
foreach (var record in records)
{
_sqlConnectionDataService.UnlockRecord(record.ID);
}
}
}
SqlConnectionDataService.cs
public void UnlockRecord(int recordId)
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Sqlconnection"].ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = #"UPDATE [Records] SET [IsLocked] = 0";
//etc
command.ExecuteNonQuery();
}
}
}
App.config
<add name="EntityConnection" connectionString="metadata=res://*/FooDatabase.csdl|res://*/FooDatabase.ssdl|res://*/FooDatabase.msl;provider=System.Data.SqlClient;provider connection string="data source=RemoteServer;initial catalog=FooDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="SqlConnection" connectionString="Server=RemoteServer;Database=FooDatabase;Trusted_Connection=True" />
Now, after discussing with my coworkers, I ended up moving the logic into the entity framework dataservice and doing the work there. But I'm still not quite sure why the connection kept failing.
Edit: The actual error is:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Inner Exception:
The network path was not found
But Entity Framework is using the same network path, as can be seen in the two connection strings in the App.config.
Could you be benefiting from entity framework's new resiliency, where it retries transparently? If the error is intermittent, you won't even know it retried, whereas ADO.net is letting you know it fails as soon as it fails. Just checking...
I try to deploy my project into Azure, and while the publishing is successful, I always get the "A network-related or instance-specific error occurred while establishing a connection to SQL Server. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)" error.
I read/watched a few tutorials about publishing an asp.net project via Visual studio, and I noticed a difference between my project and those in the tutorials:
While others had only one database in the "Settings" section of their Publish window, I have two, and I don't know why. I figured that this may be the reason I get the error.
Here's my window:
And here's one from a tutorial:
I don't really get this, because I should have only one database, like my server explorer shows:
In my web.config file there's only one connection string defined, and that's for the DefaultConnection:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-vocab_2-20130928092402;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-vocab_2-20130928092402.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
I guess my DbContext-derived VocabModel class is also relevant:
public class VocabModel : DbContext
{
public VocabModel() : base("name=DefaultConnection")
{
if (Membership.GetUser()!=null)
{this.currentuser = UserProfiles.Find((int)Membership.GetUser().ProviderUserKey);}
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<ForeignExpression> ForeignExpressions { get; set; }
public DbSet<PracticeResult> latestResults { get; set; }
}
So what's wrong? Did I make a fundamental error with Entity Framework? (this is the first time I'm using it)
Well, it was the
if (Membership.GetUser()!=null)
{this.currentuser = UserProfiles.Find((int)Membership.GetUser().ProviderUserKey);}
part in my model's constructor. I moved this code to the get method of the currentuser property (which is more logical anyway), and now it works as expected. Any explanation would still be appreciated. (Why did that part cause an additional database during publish?)