Foreign Key Causes WCF Socket Connection to Abort - c#

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!

Related

Can't initialize local SQL Server database with EFCore commandline tools

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.

EntityException: The underlying provider failed on Open + inner exceptions

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.

My E2E tests on my webapi/signalr app run successfully individually but not if batched

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.)

Asp.Net MVC3 Ado.Net Entity Data Model timeout error - Entity Framework Command execution timeout error

First let me clarify, I searched stackoverflow solutions for this, and whatever I found didn't resolve this error in my situation. Users keep getting this error every now and than and when they re-query or refresh the page data appear fine without error. This behavior is certainly irritating the users even if they get a user-friendly message instead of Asp.net YSOD.
Complete error message:
System.Data.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
To give a brief overview about the application: It's a .Net MVC3 application. There is separate project for Business logic and separate project for UI (Controller and Views etc..). Business logic project contains Data layer which is ADO.NET Entity Data Model (I believe entity framework 4.1). The EF contains only Sql Server Store Procedures (there are no tables/views etc..). All communications to the database happen through SPs function imports. The business project queries the SPs and returns IQueriable type business object, which eventually we use in controller and return as JSON objects to the jQuery AJAX call. Our SQL serve DB is 2012.
One solution resolves this issue temporarily is when I restart the IIS 7.
What I have tried so far and have not been able to resolve this issue:
Increased EF Command Execution timeout.
used below using pattern
using (DbContext context = new DBContext())
{
context.Connection.Open();
//All EF code goes here.
context.Connection.Close();
}
Updating the model from DB and recreating all the function imports fresh.
Database side tuning up to improve the query performance.
Some more...unable to recall right now.
Please let me know if you need any other information. Any help will be very much appreciated.

Entity Framework errors when calling an ASP.NET hosted WCF Service concurrently

I have a simple ASP.NET hosted WCF Service that has several methods that all have the same pattern when it comes to using the Entity Framework...
public void Operation1(string username)
{
using(MyEFContext context = new MyEFContext())
{
UserInfo info = (from ui in context.UserInfos
where ui.User.Equals(username)
select ui).FirstOrDefault<UserInfo >();
info.LastAccess = DateTime.Now;
// Operation specific code, such as getting information using the EF context
context.SaveChanges();
}
}
This is a cut down version to keep the example simple but even this simple version has the same error as my production set of code. The code starts by getting the users information using the Entity Framework, updates the users LastAccess field and then performs the operation specific code. The operation specific code just makes queries for information. At the end it calls SaveChanges so the LastAccess is saved back to the database. Now this all works perfectly fine until my client makes two calls in parallel.
The client makes two calls, each to a different operation but they both have the same pattern of code as seen above. Sometimes both calls complete with success. But other times one of them will produce as error and it could be any of the following three...
System.Data.EntityException: The underlying provider failed on Open. --->
System.InvalidOperationException: The connection was not closed. The connection^s current
state is connecting.
System.Data.EntityCommandExecutionException: An error occurred while executing the command
definition. See the inner exception for details. ---> System.InvalidOperationException:
ExecuteReader requires an open and available Connection. The connection^s current state is
closed.
System.InvalidOperationException: Invalid attempt to read when no data is present.
Clearly my understanding of EF and ASP.NET is flawed because I expected the two operations to work even in parallel. Do I need to put a lock around each method so they only occur one at a time? Surely not. Any ideas?
Found the answer here Managing EntityConnection lifetime. Turns out that reusing the same EntityConnection instance for all my contexts was the issue. So now I create a new one each time.

Categories

Resources