I apologize in beforehand because I see that a lot of people have already answered this question but still I cannot find the answer I am looking for.
In my solution I got 5 projects where 2 are C# libraries (the Core layer and the Data layer). The other 3 are using the Core layer to connect to the data layer and these three are a web-API project, a test winform project and a MVC project. I am currently trying out the winform project and that is where the error occurs. The API project works fine when connecting to database.
As the title suggest I have gotten this common exception in the winform project
System.Data.DataException: 'An exception occurred while initializing
the database. See the InnerException for details.'
EntityException: The underlying provider failed on Open.
with the following inner exceptions
SqlException: Connection Timeout Expired. The timeout period elapsed
while attempting to consume the pre-login handshake acknowledgement.
This could be because the pre-login handshake failed or the server was
unable to respond back in time. The duration spent while attempting
to connect to this server was - [Pre-Login] initialization=38878;
handshake=35;
Win32Exception: The wait operation times out
The errors occurs in my Datacontext on Database.Initialize(true);:
public class DataContext : DbContext
{
public DataContext() : base("HololensRegistreringsskyltar")
{
Database.SetInitializer(new DataContextInitializer<DataContext>());
Database.Initialize(true);
}
}
I am also using generic repository pattern with Unit Of Work if that matters (and I am new to it).
Btw there is only a connection string in the API projects web.config, maybe there should be in the other two "outer" layers too?
Can anyone tell me how to solve this issue and making it work for all 3 "outer" layers?
Following cases can cause this exception:
An instance of the SQL Server Database Engine is not running.
The SQL Server Browser service is not running.
The TCP/IP is disabled.
The server name was typed incorrectly.
There are network problems.
The TCP/IP port for the Database Engine instance is blocked by a firewall.
The client and server are not configured to use the same network protocol.
Related
I've been trying to follow several different tutorials with EFCore and .net core and I've been totally blocked at the point where I try and create a local database.
I've used both the powershell tools and the commandline tools to try and create an initial migration (or do anything, really).
I consistently get the error:
System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseSqlServer' call.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: Named Pipes Provider, error: 0 - No process is on the other end of the pipe.)
The database does not currently exist on the system, though local SQL Server appears to be up and running.
Here is the c# code for adding the context:
services.AddDbContextPool<TestDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TestDb")
)
);
This is the connection string code:
"TestDb": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=TestDb"
I get similar errors whether I run add-migration, dotnet ef migration add, or dotnet ef dbcontext info. (note: with the dotnet calls I am using the -s ..\{webproject}\{webproject}.csproj property
I've also messed with the connection string by adding various combinations of Trusted_Connection=True; MultipleActiveResultSets=True;, and Integrated Security=true.
I've gone into SSMS and ensured the Server authentication is SQL Server and Windows Authentication Mode and that Maximum Connections is set to 0 (unlimited). I've also gone to logins and tried adding the user to pretty much all the server roles.
So, yeah, I'm pretty confused. I've worked with EF for years, though this is my first experience with EFCore and I'm definitely more of a developer than a SQL Admin. This is also my first time trying to use the local db on this particular computer.
Edit: Looking at error.log in AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\mssqllocaldb I see this error:
2020-01-28 10:15:03.50 Logon Error: 18456, Severity: 14, State: 38.
2020-01-28 10:15:03.50 Logon Login failed for user 'LAPTOP-NC6HQ4TB\ripli'. Reason: Failed to open the explicitly specified database 'TestDb'. [CLIENT: <named pipe>]
Which is confusing. Of course I can't open the specified database. The entire point is I want to create a DB that doesn't yet exist.
Found the answer. Sorry to everyone who tried to help, as you wouldn't have had enough information to solve it.
In the DbContext I had tried to add some code to the constructor to try and populate some data to the database as part of a test. This caused several problems. If the Database hadn't yet been created it tried to connect to the DB before it had been created, which caused the problems I described.
Furthermore, if I had created the db manually it would try to access the DbSets (which had not yet been created), and then complain that the set name was invalid (which, at this point it was.
This all might have been fine if the DB had been created in advance, but since I was using the DbContext to construct the database, it understandably caused problems.
And all of this headache would have been avoided had I not violated SRP and not tried to (even temporarily) hijack a context constructor to hack in some test data.
The takeaway here? Don't pollute your constructors with unrelated hacks. Bleh.
I'm aware there a bunch of questions about this error already, but many of them don't have an answer, and I'm struggling to get a handle on how to troubleshoot it.
I have a Windows service which scans a drop folder for the presence of a file and springs into action when it finds one. From time to time - often, it seems, when it's been inactive for a while, it throws this error:
MySql.Data.MySqlClient.MySqlException (0x80004005): Fatal error encountered during command execution.
---> System.IO.IOException: Unable to write data to the transport connection: An established connection was aborted by the software in your host machine.
---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine
Here are the first few lines of code that are executed:
FileQueue fq = _rep.GetFile(file.FileId);
_log.Info(string.Format("Processing file {0} for job {1}", file.FileId, file.Job.Description));
SetJobToProcessing(file);
_rep is an instance of a repository class built on Entity Framework and connecting to MySql. The logger is NLog which writes to a log table in the same database. The instance is created when the windows service starts up. Here are are the relevant function definitions:
public void SetJobToProcessing(FileQueue file)
{
file.Job.Status = JobStatus.Processing;
_rep.Update(file);
_rep.SaveChanges();
}
And from the repository:
public FileQueue GetFile(params object[] keyValues)
{
return FileQueues.Find(keyValues);
}
public void Update<T>(T updateItem) where T : class
{
Set<T>().AddOrUpdate(updateItem);
}
public int SaveChanges()
{
this.SaveChanges();
}
The error is intermittent but seems to occur when service hasn't had anything to do for a while. So I presumed this was some kind of timeout of keepalive issue.
But then I noticed that it's occurring on the call to SetJobToProcessing. That's the third call to the database in the sequence - the file is fetched first, then the action logged, and then it errors updating and saving data.
What can I do to solve or further investigate this issue? Should I be writing some sort of connection re-test function to try twice if it fails? Maybe creating and disposing of a repository object for each time the service polls the folder instead of on instantiation?
We have entity framework implemented in our Web API 2.0 code. To call database entities, we are using store procedure calls. Our entire application is hosted in Microsoft Azure cloud. Here are the two exception which we are facing.
Message : An error occurred while executing the command definition. See the inner exception for details.
InnerException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. This failure occured while attempting to connect to the Principle server.
One more exception we are facing is like:
Message : The underlying provider failed on Open.
InnerException: The connection was not closed. The connection's current state is connecting.
Note: Code is in C# Web API 2.0. We are using Entity Framework to call Store Procedure. Database is in SQL Server 2012. In web.config, the connection string looks like below:
<add name="*****Entities" connectionString="metadata=res://*/Models.Database.*****.csdl|res://*/Models.Database.*****.ssdl|res://*/Models.Database.*****.msl;provider=System.Data.SqlClient;provider connection string="data source=*****;Failover Partner=*****;initial catalog=*****;user id=*****;password=********;MultipleActiveResultSets=True;Pooling=false;Connection Lifetime=2;App=EntityFramework"" providerName="System.Data.EntityClient" />
Also, this errors are not continuous, we guess this might be happening either network issues or while heavy traffic. But we are still not having any firm cause about this.
Please guide us with a solution for the same.
This looks like Transient Fault error to me.
You should use EF6 (or later) and setup the Execution Strategies.
If it matters I'm using:
xUnit for the test runner
C# 4.5.1 (so that I can take advantage of TransactionScopeAsyncFlowOption.Enabled and just rollback a transaction across threads - [AutoRollback] didn't work)
Protractor.NET for the browser/driver (the client uses Angular)
Owin to self-host the site (if that's the right term)
EntityFramework to set up the test data before each test and in my app to do most data access
When I run each test individually by right-clicking it, everything works fine. However whenever I run them all using the Test Runner/Test Explorer all but the first throw exceptions.
I'm following the Arrange-Act-Assert pattern. During "Arrange" I call DbContext.SaveChanges(). That's when this error is thrown:
Result Message:
System.Exception : The underlying provider failed on Open.
---- System.Data.Entity.Core.EntityException : The underlying provider failed on Open.
-------- System.Transactions.TransactionException : The operation is not valid for the state of the transaction.
------------ System.Transactions.TransactionPromotionException : Failure while attempting to promote transaction.
---------------- System.Data.SqlClient.SqlException : There is already an open DataReader associated with this Command which must be closed first.
-------------------- System.ComponentModel.Win32Exception : The wait operation timed out
I've tried googling several of the errors. Enabling MARS in my connection string didn't fix it. Extending the Timeout in my connection string didn't fix it.
I figured: maybe someone knows something about this pattern of nested exceptions and could shed some light on a precise issue.
If not, what are my next diagnostic steps to figure out why the exception is being thrown?
I was explicitly creating a SqlConnection/SqlDataAdapter in a WebApi endpoint of my code that creates a SQL query dynamically that tests 2 and 3 were calling and test 1 wasn't. The outermost rollback transaction I described in my question along with the SqlConnection were causing the connection.Open() call in the WebApi endpoint to promote to being handled by the DTC.
I discovered this by putting this in my bootstrap code:
TransactionManager.DistributedTransactionStarted += TransactionManager_DistributedTransactionStarted;
// ...
void TransactionManager_DistributedTransactionStarted(object sender, TransactionEventArgs e)
{
throw new Exception("DistributedTransactionStarted");
}
For the time being (I'll only do the following during these E2E tests ultimately) I rewrote my Ninject code to use singletons for SqlConnections and made it so the DbContext does not own the connection. This solved the exception I was getting above so therefore answers the question (even though I'm getting a different error now). (I think I also ended up putting MARS back in my connection string, but that may have been for a different exception - can't remember.)
I have 2 tables, Unit and SubUnit, with a one to many relationship: a Unit can have 0 or more SubUnits.
I use Linq to SQL (.dbml files) in a WCF Windows Service to access the database.
Using the Service Client, I call any method to retrieve either the Units or the SubUnits and it works fine...as long as there are no SubUnits in the database (0 rows in the SubUnit table).
If there is 1 or more SubUnits, I get the following errors when calling the same methods:
"The socket connection was aborted..."
with inner exception "The read operation failed, see inner
exception."
with inner exception "The socket connection was
aborted..."
with inner exception "An existing connection was forcibly
closed by the remote host"
I've dropped the tables and re-created them, I've re-added the Unit/SubUnit tables to the DBML, re-installed the service, etc. I've never run into this problem before.
I understand the "Socket aborted" error can be caused by trying to pass too much data over WCF, but there is currently 1 Unit with 1 SubUnit in the database and I still get this error!
Can anyone shed some light on this?
You need to add [DataContract(IsReference = true)] attr. to your entity.
Had the exact same error/issue using a wcf client once I introduced Foreign key(s) on the db while using the Entity Framework in the wcf service.
The server-side calls and business logic to the entity framework worked just fine w/ the FK's, but client bombed when connecting to the service (returning a List).
I'm using the .edmx and also the EF 5.x DBContext Generator.
I had to Turning off lazy loading for all navigation properties.
i.e. in my model template, remove the ' virtual' keyword in the template:
public string AccessibilityAndVirtual(string accessibility)
{
return accessibility + (accessibility != "private" ? " virtual" : "");
}
see awesome post!