I just moved my MVC5 web-project to Azure. The project uses a MySql database which is now hosted in Azure as well. I have updated the connection strings, and if I start the website from localhost on my own machine (still pointing to the database on Azure) all works well. But if I start the website from my Azure url, I get an sql error.
System.Data.Entity.Core.ProviderIncompatibleException: The provider
did not return a ProviderManifestToken string. --->
MySql.Data.MySqlClient.MySqlException: Unable to connect to any of the
specified MySQL hosts. ---> System.Net.Sockets.SocketException: An
attempt was made to access a socket in a way forbidden by its access
permissions 127.0.0.1:3306 at
System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) at
MySql.Data.Common.MyNetworkStream.CreateSocketStream(MySqlConnectionStringBuilder
settings, IPAddress ip, Boolean unix) at
MySql.Data.Common.MyNetworkStream.CreateStream(MySqlConnectionStringBuilder
settings, Boolean unix) at
MySql.Data.Common.StreamCreator.GetStream(MySqlConnectionStringBuilder
settings) at MySql.Data.MySqlClient.NativeDriver.Open() --- End of
inner exception stack trace --- at
MySql.Data.MySqlClient.NativeDriver.Open() at
MySql.Data.MySqlClient.Driver.Open() at
MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder
settings) at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection() at
MySql.Data.MySqlClient.MySqlPool.TryToGetDriver() at
MySql.Data.MySqlClient.MySqlPool.GetConnection() at
MySql.Data.MySqlClient.MySqlConnection.Open() at
MySql.Data.MySqlClient.MySqlProviderServices.GetDbProviderManifestToken(DbConnection
connection) at
System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection
connection) --- End of inner exception stack trace --- at
System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection
connection) at
System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices
providerServices, DbConnection connection) --- End of inner exception
stack trace --- at
System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices
providerServices, DbConnection connection) at
System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.<>c__DisplayClass1.b__0(Tuple3
k) at
System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey
key, Func2 valueFactory) at
System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveManifestToken(DbConnection
connection) at
System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection
connection, DbProviderManifest& providerManifest) at
System.Data.Entity.DbModelBuilder.Build(DbConnection
providerConnection) at
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext
internalContext) at
System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) at
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() at
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type
entityType) at
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() at
System.Data.Entity.Internal.Linq.InternalSet1.Include(String path) at
System.Data.Entity.Infrastructure.DbQuery1.Include(String path) at
System.Data.Entity.QueryableExtensions.Include[T](IQueryable1 source,
String path) at
System.Data.Entity.QueryableExtensions.Include[T,TProperty](IQueryable1
source, Expression1 path) at
Microsoft.AspNet.Identity.EntityFramework.UserStore6.GetUserAggregateAsync(Expression1
filter) at
Microsoft.AspNet.Identity.EntityFramework.UserStore6.FindByNameAsync(String
userName) at
Microsoft.AspNet.Identity.UserManager2.FindByNameAsync(String
userName) at
Microsoft.AspNet.Identity.Owin.SignInManager2.<PasswordSignInAsync>d__29.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
tripplanner.Controllers.AccountController.<Login>d__2.MoveNext() ---
End of stack trace from previous location where exception was thrown
--- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult
asyncResult) at
System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult
asyncResult) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallEndDelegate(IAsyncResult
asyncResult) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End()
at
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult
asyncResult) at
System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at
System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at
System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallEndDelegate(IAsyncResult
asyncResult) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult
asyncResult) at
System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.b__1c()
at
System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__1e(IAsyncResult
asyncResult);
Hope someone can help.
UPDATE: I was using the wrong web.config file in Azure.
Related
I'm using asp.net MVC with mysql database. I have MySql.Data v8.0.16.0 and MySql.Data.EntityFramework v8.0.16.0 installed.
Mysql provider added in web.config:
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework, Version=8.0.16.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
</provider>
I'm using asp.net Idnetity. Here is the configuration:
[DbConfigurationType(typeof(MySql.Data.EntityFramework.MySqlEFConfiguration))]
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ApplicationUser>().ToTable("aspnetusers");
modelBuilder.Entity<IdentityRole>().ToTable("aspnetroles");
modelBuilder.Entity<IdentityUserRole>().ToTable("aspnetuserroles");
modelBuilder.Entity<IdentityUserClaim>().ToTable("aspnetuserclaims");
modelBuilder.Entity<IdentityUserLogin>().ToTable("aspnetuserlogins");
base.OnModelCreating(modelBuilder);
}
}
On my local pc, everything works fine, but on hosting server i get error, here is the complete exception with stack trace:
System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> MySql.Data.MySqlClient.MySqlException: Table 'live-db-373103e4.AspNetUsers' doesn't exist at MySql.Data.MySqlClient.MySqlStream.ReadPacket() at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId) at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId) at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force) at MySql.Data.MySqlClient.MySqlDataReader.NextResult() at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior) at MySql.Data.EntityFramework.EFMySqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.d__c.MoveNext() --- End of inner exception stack trace --- at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.d__c.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.d__0`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter`1.GetResult() at System.Data.Entity.Core.Objects.ObjectContext.d__3d`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter`1.GetResult() at System.Data.Entity.Core.Objects.ObjectQuery`1.d__e.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter`1.GetResult() at System.Data.Entity.Internal.LazyAsyncEnumerator`1.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.d__25`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNet.Identity.TaskExtensions.CultureAwaiter`1.GetResult() at Microsoft.AspNet.Identity.EntityFramework.UserStore`6.d__67.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at Inspinia_MVC5_SeedProject.Controllers.AccountController.d__7.MoveNext() in C:\Users\mirfa\source\repos\dealkar-refactored-2019\Inspinia_MVC5_SeedProject\Controllers\AccountController.cs:line 139 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass8_0.b__1(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_0.b__0() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass7_0.b__1(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_6.b__4() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.b__1(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) at System.Web.Mvc.Controller.<>c.b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End() at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) at System.Web.Mvc.Controller.<>c.b__151_2(IAsyncResult asyncResult, Controller controller) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End() at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) at System.Web.Mvc.MvcHandler.<>c.b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End() at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
server db version is: 10.1.35-MariaDB.
these tables exist on server:
How can I solve the exception of table does not exist?
Update:
The code first migration is creating table name in upper case.i.e, AspNetUsers instead of aspnetusers. Shouldn't it create tables with lower case?
public partial class added_aspnetusers : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.String(nullable: false, maxLength: 128, storeType: "nvarchar"),
status = c.Int(nullable: false),
//other columns
});
}
}
Update:2
modelBuilder.Entity<ClassName>().ToTable("table_name");
entity framework is not changing name of table for any entity.
You're calling base.OnModelCreating(modelBuilder) after customizing your table names.
That method configures the Identity table names, overwriting yours.
Move that line to the top of your overridden method.
I am getting the following error when trying to create a new user using the UserManager CreateAsync method. I am using an unmodified IdentityUser and IdentityRole. I have a few DBSets which populate with data from the database, so reading is not an issue, just writing to it seems to be.
{System.InvalidOperationException: Connection must be valid and open to commit transaction at MySql.Data.MySqlClient.MySqlTransaction.Commit()
at Microsoft.EntityFrameworkCore.Storage.RelationalTransaction.Commit()
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.<ExecuteAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__54.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__52.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.DbContext.<SaveChangesAsync>d__35.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.<CreateAsync>d__36.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Identity.UserManager`1.<CreateAsync>d__68.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Identity.UserManager`1.<CreateAsync>d__73.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Controllers.Auth.AuthController.<Register>d__9.MoveNext() in AuthController.cs:line 102}
I'm using;
MySQL Entity Framework Core 7.0.7-m61
Visual Studio 2017
ASP.NET Core MVC 1.1.0
Identity 1.1
Line 102 mentioned in the error is var result = await userManager.CreateAsync(newUser, model.Password);
[HttpPost]
public async Task<ActionResult>Register(RegisterViewModel model)
{
try
{
if (ModelState.IsValid)
{
var newUser = new IdentityUser
{
Email = model.Email,
UserName = model.Username
};
var result = await _userManager.CreateAsync(newUser, model.Password);
if (result.Succeeded)
{
await _signInManager.SignInAsync(newUser, false);
_logger.LogInformation($"New user account created: {model.Username}");
return RedirectToAction("Index", "App");
}
_logger.LogError($"Registration failed for {model.Username}: ", result.Errors);
return View(model);
}
return View(model);
}
catch (Exception ex)
{
_logger.LogError("Database Failure: ", ex);
return View(model);
}
}
I'm learning asp.net and am stumbling here on what I'm hoping is an obvious error as it seems to be a basic connection issue but it's not making sense as the database can be queried using IdentityDBContext but not through the UserManager, which in my understanding uses the IdentityDBContext connection.
Do not use MySql.Data.EntityFrameworkCore-7.0.7-m61 provider and use something else. Oracle manages to embarrass themselves with each pre-release version of it.
With this release they managed to brake the package so hard, that it's unusable as that provider seems to close it's connection after every query. Use Pomelo.EntityFrameworkCore.MySql 1.1.0 instead (or wait for the next release of Oracles provider). Oracle was never strong at supporting ADO.NET/EF with current provider versions
Even better, use PostgreSQL or SqlServer instead.
I created a small ASP.NET core web api using MVC and Entity Framework. I managed to build and publish it for/to Ubuntu.
When I enter the url swagger shows up as expected. But when I try to access a resource (click a link to the web api) it throws an exception in the log files indicating that it can not access the database.
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: TCP Provider, error: 35 - An internal exception was caught) ---> System.AggregateException: One or more errors occurred. (No such device or address) ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: No such device or address
at System.Net.Dns.HostResolutionEndHelper(IAsyncResult asyncResult)
at System.Net.Dns.EndGetHostAddresses(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Data.SqlClient.SNI.SNITCPHandle.d__22.MoveNext()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait(TimeSpan timeout)
at System.Data.SqlClient.SNI.SNITCPHandle..ctor(String serverName, Int32 port, Int64 timerExpire, Object callbackObject, Boolean parallel)
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open()
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.d__3`1.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.d__15`2.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter.WriteObject(TextWriter writer, Object value)
at Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter.d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__32.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__31.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__29.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.ApplicationInsights.AspNetCore.ExceptionTrackingMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.ApplicationInsights.AspNetCore.RequestTrackingMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1.d__2.MoveNext()
Well, the database is on a different machine. It is pingable, responding from another machine and even with commandline tool you can query the database from the linux commandline.
The connection string is the same as on the windows machine definind ip address, server name, user id and password.
Are there any dependencies that has to be installed or is there a need for some (not that well documented) configuration changes I am missing?
There are already a couple of questions and answers on that but no answer was able to solve the problem for me.
Things I tried so far:
check if config files are copied to the server -> they are
hardcode connection string -> works from Win7 but not on Ubuntu
adding explicit port to the connection string -> no change
adding semicolon at the end of the connection string -> no change
check if TCP/IP and named pipes are enabled on the SQL Server -> they are
ping the server from the Ubuntu machine -> SQL server is pingable
test it with Debug and Release version -> same error
update all Nugets to neweset versions -> no change
adding System.Data.SqlClient to the project.json -> no change
use TSQL from the Ubuntu shell to test the server -> using TSQL it works
out of curiosity I followed that guide and got it working -> still same error
Update:
There is not much configuration. The code is simple in the Startup.cs
public void ConfigureServices(IServiceCollection services) {
services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
//configs of other parts
}
in appsettings.json
"ConnectionStrings": {
"DefaultConnection": "Server=xxx.xxx.xxx.xxx;Database=DatabaseName;user id=*****;password=*****"
},
I blanked out the ip address, gave another db name and inserted some stars for the user id and passwort.
None the less it works on my win7-x64 machine as is.
Well, the problem was simply a mistake by myself.
I scaffolded the DbContext from an existing database. By that I missed that scaffolding adds a HARDCODED connection string into the OnConfigure method. This connection string pointet too a different (no longer existing) database.
So all my approaches to connect or changing the connection strings in the appsettings.json etc just got overwritten by the hardcoded connection string and for that failed.
I am getting this error in my recently deployed MVC 4 web application, whenever I click a link that requires database access:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
When I run the mvc app locally, through visual studio, connecting to these remote databases, I do not get this error, and the credentials are correct because when I "Connect to database" it logs in and retrieves all the entities as normal. I published the site to the server's FTP, as the host does not have a webdeploy service.
Can anyone explain why my deployed app would have issues with the database and not my local version?
UPDATE
Before I exposed this NullReferenceException, it was a ReflectionTypeLoadException. Don't know if that means anything, but here:
[ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.]
System.Reflection.RuntimeModule.GetTypes(RuntimeModule module) +0
System.Reflection.RuntimeModule.GetTypes() +4
System.Reflection.Assembly.GetTypes() +61
System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.<.ctor>b_1(Assembly a) +11
System.Linq.d_142.MoveNext() +234
System.Collections.Generic.List1.InsertRange(Int32 index, IEnumerable1 collection) +392
System.Data.Entity.ModelConfiguration.Mappers.TypeMapper..ctor(MappingContext mappingContext) +258
System.Data.Entity.DbModelBuilder.MapTypes(EdmModel model) +114
System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo) +112
System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +59
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +62
System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) +123
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +461
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +52
System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext() +15
System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider() +37
System.Linq.Queryable.Select(IQueryable1 source, Expression1 selector) +66
ProOptInteractive.Controllers.ServiceController.Index() +115
lambda_method(Closure , ControllerBase , Object[] ) +35
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +182
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass81.b__7(IAsyncResult ) +10
System.Web.Mvc.Async.WrappedAsyncResult1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +58
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c_DisplayClass2a.b_20() +24
System.Web.Mvc.Async.<>c_DisplayClass25.b_22(IAsyncResult asyncResult) +99
System.Web.Mvc.Async.WrappedAsyncResult1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult1.End() +55
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
System.Web.Mvc.Async.<>c_DisplayClass4.b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult1.End() +55
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult1.End() +55
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9628700
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Update
Ok I just attempted to deploy a brand new MVC app from Visual Studio, and that gave me no errors when trying to access models (I made a simple Students model and created a new "Student" in the database, something that would not work in my actual MVC app. Any ideas?
The table in the database might not exist. I am facing the same problem now, the easiest way is to delete the whole DB and let EF recreate everything. If you already have some sensitive data, then it is trickier. And you might try these too:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<YourDbContext>());
// or you can use DropCreateDatabaseAlways<>
From here: EF4 Code First create new table
Or you can check this one: Entity Framework 4.1 Code First not creating tables
I'm trying to connect to localhost:45000 (it is a tunnel to my pagodabox MySQL)
But in webmatrix I get this error:
Call to GetHostEntry failed after 00:00:00 while querying for hostname 'localhost:45000': SocketErrorCode=HostNotFound, ErrorCode=11001, NativeErrorCode=11001.
MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts. ---> System.Exception: Call to GetHostEntry failed after 00:00:00 while querying for hostname 'localhost:45000': SocketErrorCode=HostNotFound, ErrorCode=11001, NativeErrorCode=11001. ---> System.Net.Sockets.SocketException: No such host is known
at System.Net.Dns.GetAddrInfo(String name)
at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)
at System.Net.Dns.GetHostEntry(String hostNameOrAddress)
at MySql.Data.Common.StreamCreator.GetDnsHostEntry(String hostname)
--- End of inner exception stack trace ---
at MySql.Data.Common.StreamCreator.GetDnsHostEntry(String hostname)
at MySql.Data.Common.StreamCreator.GetHostEntry(String hostname)
at MySql.Data.Common.StreamCreator.GetStreamFromHost(String pipeName, String hostName, UInt32 timeout)
at MySql.Data.Common.StreamCreator.GetStream(UInt32 timeout)
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at Microsoft.WebMatrix.DatabaseManager.MySqlDatabase.MySqlDatabaseProvider.TestConnection(String connectionString)
at Microsoft.WebMatrix.DatabaseManager.IisDbManagerModuleService.TestConnection(DatabaseConnection databaseConnection, String configPathState)
at Microsoft.WebMatrix.DatabaseManager.Client.ClientConnection.Test(ManagementConfigurationPath configPath)
at Microsoft.WebMatrix.DatabaseManager.Client.DatabaseHierarchyInfo.EnsureLoaded()
Is it that webmatrix can't handle the 45000 port? (It works otherwise (in MySQL-WorkBench).)