Entity Exception : the underlying provider failed to open - wcf

iv'e got a wcf service host hosting a service on IIS7,
iv'e added a database to it's App_Data folder ,
the service is referenced to a DAL project
which holds an Entity Framework model generated from my DB ( The DB from the WCF Service Host )
i keep getting the above entity exception with this inner message :
{"An attempt to attach an auto-named database for file C:\\Users\\eranot65\\Documents\\Visual Studio 2010\\Projects\\CustomsManager\\WcfManagerServiceHost\\App_Data\\CustomesDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."}
iv'e copied the connection string from DAL/app.config to WcfManagerServiceHost/Web.config
add name="CustomesDBEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string='Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Users\eranot65\Documents\Visual Studio 2010\Projects\CustomsManager\WcfManagerServiceHost\App_Data\CustomesDB.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True'" providerName="System.Data.EntityClient"
this happens when i try to use my data source entity model:
public List<Employee> GetEmployees()
{
List<Employee> employees = null;
using (CustomesDBEntities entites = new CustomesDBEntities())
{
employees = entites.Employees.ToList<Employee>();
}
return employees;
}
it doesn't seem as if the DB is in use some where else ,
(1) how can i check if some other process is holding a handle to my DB ?
(2) in ideas this happens ?

I would consider checking one of two things:
Create a connection to your SQL Express, either in VS server explorer, or by using the SQL management studio, and verify you do not already have a database by that name attached to your server.
Move your project from it's current location to somewhere on the disk which is not user-specific (meaning not on the desktop, documents etc..), for example - c:\temp, c:\projects... The reason for that is that you are running a web application, and in case you run it in IIS, the identity of the worker process is a special identity other than yours which might not have permissions to access the database file since it is located in a private folder of your user

Most likely the problem is that you are opening the database with Visual Studio and your application at the same time. The connection string explicitely configures AttachDbFilename=... AttachDBFilename spins up a user instance of SQL Express attached to a specific DB Filename for single user mode. In single user mode, only one application can open the MDF at a time.

well the answer is always simpler then you would think
all i ended up doing is changing to automatically generated connection string
generated by the EntityFramework model , to a connection string to locate the DB in my App_Data folder
my original connection string :
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string='Data
Source=.\SQLEXPRESS;AttachDbFilename="C:\Users\eranot65\Documents\Visual Studio 2010\Projects\CustomsManager\WcfManagerServiceHost\App_Data\CustomesDB.mdf"
;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True'" providerName="System.Data.EntityClient"
my edited connection string :
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;
provider connection string='Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\CustomesDB.mdf;Integrated Security=True;;User Instance=True;MultipleActiveResultSets=True'"

Related

How to set the connection string on another computer for access database

I created very simple winform with access database, i have 3 pcs i choose one of them to host the database (shared), and i created a .udl (data link properties) on the other two computers and i configured the path for the shared database, the test connection was successful, i opened the udl file and i have the connection string Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\PCName\c$\temp\Database1.accdb;Persist Security Info=False My question, where will i put the connection string? do i need to have the program solution just to put it?
You can define the connection string in app.config

SQL Server Express dev setup - access denied whack-a-mole

I have a development environment in which I need to use IIS and SQL Server Express. My connection string looks like this:
<add name="DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyProject.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
This works great when I run the app and browse to the site. Data is returned from the database and I can log into Management Studio and view that data. The problem is when I try to push a new data migration using Update-Database.
I then get this error message:
Login failed for user 'AzureAD\MyAccount'
If I remove User Instance=True from my connection string, the Update-Database command suddenly works! Then I refresh my page and see the following error from all endpoints that require the database:
CREATE DATABASE permission denied in database 'master'.
I have already tried the trick of deleting this folder. It did not solve it.
C:\Users\MyAccount\AppData\Local\Microsoft\Microsoft SQL Server Data
What gives?
Figured this out so Ill leave the answer here for the next dev:
As I mentioned, my dev setup is running IIS and SQL Express.
Update the connection string to point to an Initial Catalog=MyDatabase instead of the AttachDbFilename=|DataDirectory|\MyProject.mdf
Remove User Instance=True. Your connection string now looks like:
Data Source=.\SQLEXPRESS;Initial Catalog=FullStackFitness;Integrated Security=True
Create the database by running Update-Database.
Create a SQL login for the app pool account (IIS APPPOOL\ACCOUNT) dbcreator and sysadmin on the database.
I did not test it but I believe you can keep using an mdf file and still get this to work by running only steps 2 - 4.
Troubleshooting Tips
Help troubleshooting the access denied issue came from a tip on Scott Allens blog:
The first step I would recommend is trying to determine what connection string the framework is using, because the exception doesn’t tell you the connection string, and the connection string can be controlled by a variety of conventions, configurations, and code.
To find out the connection string, I’d add some logging to a default constructor in my DbContext derived class.
public class DepartmentDb : DbContext
{
public DepartmentDb()
{
Debug.Write(Database.Connection.ConnectionString);
}
public DbSet<Person> People { get; set; }
}
Run the application with the debugger and watch the Visual Studio Output window. Or, set a breakpoint and observe the ConnectionString property as you go somewhere in the application that tries to make a database connection.

SqlException - The network path was not found

I'm running my code and getting this error. But what does it mean?
The network path was not found 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.ComponentModel.Win32Exception: The network path was not found
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[Win32Exception (0x80004005): The network path was not found]
[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: Named Pipes Provider, error: 40 - Could not
open a connection to SQL Server)]
This is probably related to your database connection string or something like that.
I just solved this exception right now. What was happening is that I was using a connection string intended to be used when debugging in a different machine (the server).
I commented the wrong connection string in Web.config and uncommented the right one. Now I'm back in business... this is something I forget to look at after sometime not working in a given solution. ;)
You will also get this exact error if attempting to access your remote/prod db from localhost and you've forgotten that this particular hosting company requires VPN logon in order to access the db (do i feel silly).
There may be some reasons like:
Wrong SQL connection string.
SQL Server in services is not running.
Distributed Transaction Coordinator service is not running.
First try to connect from SQL Server Management Studio to your Remote database. If it connects it means problem is at the code side or at Visual Studio side if you are using the one.
Check the connectionstring, if the problem persists, check these two services:
Distributed Transaction Coordinator service
SQL Server services.
Go in services.msc and search and start these two services.
The above answer works for the Exception:
[Win32Exception (0x80004005): The network path was not found]
Possibly also check the sessionState tag in Web.config
Believe it or not, some projects I've worked on will set a connection string here as well.
Setting this config to:
<sessionState mode="InProc" />
Fixed this issue in my case after checking all other connection strings were correct.
Same problem with me. I solved this by adding # before connection string (C# has a thing called 'String Literals') like so:
SqlConnection sconnection = new SqlConnection(#"Data Source=(Localdb)\v11.0; Initial Catalog=Mydatabase;Integrated Security=True");
sconnection.Open();
As others pointed out this could be more to do with the connectionstring config
Make sure,
user id and password are correct
Data Source is pointing to correct one , for example if you are using SQL express it will be .\SQLEXPRESS
Database is pointing to correct name of database
Hope that helps.
check your Connection String Properly.
Check that the connection is open.
String CS=ConfigurationManager.COnnectionStrings["DBCS"].connectionString;
if(!IsPostBack)
{enter code here
SqlConnection con = new SqlConnection(CS);
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblCountry", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
//Bind data
}
I recently had the same issue. It's more likely that your application can not connect to database server due to the network issues.
In my case I was connected to wrong WiFi.
At The Beginning, I faced the same error but with a different scenario.
I was having two connection strings, one for ado.net, and the other was for the EntityFramework, Both connections where correct. The problem specifically was within the edmx file of the EF, where I changed the ProviderManifestToken="2012" to ProviderManifestToken="2008" therefore, the application worked fine after that.
In my case, I had generated DbContext from an existing database. I had my connection string set in appSettings.json file; however, when I generated the class files by scaffolding the DbContext class it had incorrect connection string.
So make sure your connection string is proper in appSettings.json file as well as in DbContext file. This will solve your issue.
On my end, the problem was an unsuccessful connection to the VPN (while working from home). And yeah, the connectionString was using a context from remote server. Which resulted in the following error:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>The network path was not found</ExceptionMessage>
<ExceptionType>System.ComponentModel.Win32Exception</ExceptionType>
<StackTrace/>
</Error>
If you are using any db , please check connection string also
When I copied my solution from my pc to another one I had to change the connection string in web.config file.
Even if you have the same database name, you should do it for the server name as well.

Entity framework work locally but not on azure

I have a web project which works perfectly locally.
But when I change the connection string in my published web site on Azure to connect to my database on SQL Azure it will start giving this error.
System.Data.Entity.Infrastructure.UnintentionalCodeFirstException: Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.
at MyClass.OnModelCreating(DbModelBuilder modelBuilder) in c:\a\src\MyProject\Model.Context.cs:line 25
at System.Data.Entity.Internal.LazyInternalContext.CreateModelBuilder()
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.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.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Select[TSource,TResult](IQueryable`1 source, Expression`1 selector)
My Config has:
<connectionStrings>
<add name="MyDBEntities" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:[Removed].database.windows.net,1433;Database=MyDB;User ID=[Removed];Password=[Removed];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"" providerName="System.Data.EntityClient" />
<add name="MyDB" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:[Removed].database.windows.net,1433;Database=MyDB;User ID=[Removed];Password=[Removed];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"" providerName="System.Data.EntityClient" />
</connectionStrings>
I tested using my unit test locally with that connection string and it works from my local machine connecting to SQL Azure database.
Any help appreciated.
I was having this exact problem today; it's my first time deploying to Azure. I've been pulling my hair out, except I don't have any left. I finally figured it out, and it's probably the same issue original poster here is having.
Just like the original poster, I tested in these configurations:
ran WCF Web App from Visual Studio against local DB -- success
deployed WCF Web App from Visual Studio to local IIS, ran against local DB -- success
ran WCF Web App from Visual Studio against Azure SQL DB -- success
deployed WCF App to Azure via Visual Studio, running against Azure SQL DB -- FAILURE!!
After reading another post (Code First vs. Database First) I got a hint. That post says that if "connection string has the metadata, EF thinks it is Model First or Database First" but if it's a "plain connection string, EF thinks it is Code First." I browsed the deployed Azure Web Site's web.config and confirmed that the connection string had the proper references to the Model-First metadata. So what was the problem???
I figured that perhaps the Azure Website wasn't reading the web.config's connection string. Thinking back to how I'd created the Azure Web Site, I remembered that I'd given the Azure SQL DB an alias with the exact same name as my connection string's 'label' in the web.config!! To clarify:
in the Azure admin console I went to the Website settings and reviewed the "connection string" settings "baked in" to my Azure web site as a side-effect of creating-website-with-DB -- connection string 'handle' was "SsnCustInfoModelContainer" -- I'd mistakenly given the connection the same 'handle'/'alias' as my web.config 'handle' for the connection string, thinking this would help. Instead, when EF looks for the connection string, it was finding this 'aliased' handle, which was a "plain" SQL connection string containing no metadata. This 'alias' masked the real connection string specified in the web.config.
So I destroyed my Azure SQL DB and my Azure Web Site. Then I recreated the Azure Web Site, but this time I asked for the connection string 'alias' of "SsnCustInfoModelContainer_Proto" for the connection to the associated Azure SQL Server. After initializing the Azure SQL DB from my local SQL Server Management Studio, I deployed the WCF web app again to the Azure Web Site (I had to download a new deployment profile, of course, to do this), I tried the app again. This time it worked -- the 'alias' "SsnCustInfoModelContainer_Proto" did not conflict with and was not found by EF. EF instead went on to find the true connection string, with all the proper metadata, in the web.config. Problem solved.

How to include .sdf database file when packaging my application

I was able to create an application in VB.net that talks to a SQL Server CE database.
Now i want to deploy this application using the publish feature with clickonce.
An issue im having tho is when I install the application on another computer it keeps looking for my sql server on my development pc.
Ive added the .sdf when i package my solution but its still an issue.
How do I change my connection string to connect to the .sdf file that I included in the package?
this is my current connection string which looks at the sql server:
connectionString = " Data Source=CHRIS-PC\SQLEXPRESS;Initial Catalog=ce_db;Integrated Security=True"
Thanks !!
connectionString = "Data Source=localhost\SQLEXPRESS;Initial Catalog=ce_db;Integrated Security=True"
or perhaps
connectionString = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\ce_db.sdf;Persist Security Info=False;";
this connection string would work if you had the database in the same directory as the executable using it.
essencially the data source is either the database server that you are connecting to, or the database file that you are connecting to.
If you are using a file then you have only one catalog. and if you are using a server then you will want to specify a specific catalog using the Initial catalog attribute of the connection string.