I am executing a simple sql against Azure SQL server.
The list returns the correct number of items but then I get these 2 errors.
List<string> makes = _context.Cars.FromSql("select distinct(make) from cars").Select( l=> l.make).ToList();
A connection was successfully established with the server, but then an
error occurred during the login process. (provider: TCP Provider,
error: 0 - An existing connection was forcibly closed by the remote
host.)
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.'
What is the issue ??
I used only "pure linq" and it works. It seems that there is an issue when trying to query SQL azure with both "pure linq" and "linq with FromSql" within the same context. Maybe the "linq with FromSql" tries to open/close a different connection.
List<string> makes = _context.Cars.Select(j => j.make).Distinct().ToList()
Related
So something very strange happened with this old C# application I started to work on. I copied it locally and I've been studying the codebase without making any changes. In fact, it ran locally every day for the past week. Again, no code changes or changing in the configuration, etc. Today, I wasn't able to run it anymore. I even cloned a fresh copy - no luck. Now it's giving me this error and I don't know why. The database is remote but I can see that it's working when RDPing. What could cause this?
public static SqlConnection OpenSqlConnection(dbConnections connection, string applicationName = null)
{
var conn = CreateSqlConnection(connection, applicationName);
conn.Open();
return conn;
}
In this line, I get the following error:
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)'
This Definitely looks like a network issue rather than anything to do with the code.
Check if Your SQL Server is accessible over the network
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 have a EF Core 2 Dbcontext injected in the usual way into all Controllers of a Web API:
services.AddDbContext<KpiContext>(options =>
options.UseSqlServer(config.ConnectionStrings.KpiDB,
providerOptions => providerOptions.EnableRetryOnFailure()));
This is injected into controllers in the standard way as, say, kpidb
and then it's passed to a static method which does this:
somestaticmethod(KpiContext kpidb) {
// create something
kpidb.Add(something);
kpidb.SaveChanges();
}
This SaveChanges() intermittently fails with:
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)
I can't see a pattern to this but it happens quite often, perhaps around 10% of the time. I've tried:
AddDbContextPool instead of AddDbContext
Using Transient scope for the context
simultaneous ping shows no network interruptions at time of failure
Using port for SQL instance to prevent enumeration makes no difference
Simple connect and SELECT every 2 seconds script from the source to target never fails
Nothing seems to make a difference. I know that DBContext isn't thread safe but there are no async EF calls to fall foul of.
Any ideas appreciated.
I have a database in azure which have standart s2 edition.In logs of my application I always see many exceptions such formats:
1.
System.Data.SqlClient.SqlException: The client was unable to establish a connection because of an error during connection initialization process before login. Possible causes include the following: the client tried to connect to an unsupported version of SQL Server; the server was too busy to accept new connections; or there was a resource limitation (insufficient memory or maximum allowed connections) on the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.) ---> System.ComponentModel.Win32Exception: An existing connection was forcibly closed by the remote host
2.
System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached
3
System.Data.SqlClient.SqlException (0x80131904): The client was unable to establish a connection because of an error during connection initialization process before login. Possible causes include the following: the client tried to connect to an unsupported version of SQL Server; the server was too busy to accept new connections; or there was a resource limitation (insufficient memory or maximum allowed connections) on the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.) ---> System.ComponentModel.Win32Exception (0x80004005): An existing connection was forcibly closed by the remote host.
I use SqlAzureExecutionStrategy so this exceptions are thrown after some number of retries.
I see different performance metrics on azure portla,but it seem they are ok.
How can I identify the problem?
I think that your database is under too heavy load, or you have some queries which are still running or not letting go of the connection.
I use this query to see what is running:
SELECT (SELECT TOP 1 SUBSTRING(s2.text,statement_start_offset / 2+1 ,
( (CASE WHEN statement_end_offset = -1
THEN (LEN(CONVERT(nvarchar(max),s2.text)) * 2)
ELSE statement_end_offset END) - statement_start_offset) / 2+1)) AS sql_statement,
s1.* FROM sys.dm_exec_requests s1
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS s2
ORDER BY 1
See if you have queries still running here or keep an eye on the CPU usage in the Azure portal.
The S2 databases aren't particularly good and it will throttle your requests so if you are doing lots of them (even small ones), it might be rejecting them.
Your retry strategy could also be making the problem worse, but throwing more requests at it when it has already been filled. You could try using an exponential back-off if this is the case.
All three could be explained by your connection pooling design. Are you re-using your connections, or is every call to the database opening it's own connection? Are you closing connections at the end of each DBContext? Are you implementing any kind of caching layer to reduce the number of round trips to your database to a minimum?
Here's a way to see if it is an issue with your pooling. From the portal go to the database in question, look at the Resource utilization graph, then hit edit.
Then add Sessions percentage and workers percentage from the select list, and hit OK.
If your pooling is an issue, you'll find that your sessions and workers percentages are high, and may be pegged at 100% for periods. If you hit 100%, you can be denied new connections for up to 5 minutes until the current sessions and workers either finish, or get killed off.
I have a C# application that needs to connect to a SQL Server DB hosted by Amazon's RDS. Fairly often it throws the error
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)
When it does this, it usually works on the next try. So I would like to add a programmatic "retry" to the queries in my app. I think that this (https://stackoverflow.com/a/4822976/1011724) looks like a good pattern to follow for this. However, that answer only retries for the following errors:
private enum RetryableSqlErrors
{
Timeout = -2,
NoLock = 1204,
Deadlock = 1205,
WordbreakerTimeout = 30053,
}
So is there a way to simply add this error? If so, what is the error code? Looking here (https://msdn.microsoft.com/en-us/library/cc645611.aspx), there is no error 40 and it also is not the exact wording of error -1.
Is my error a SqlException? If so what number? If not, how can I adapted the code from the answer linked above to account for this type of exception?