So I have a basic 3-tier application:
Data Access
Business Logic
Presentation
My Data Access layer is a class library, and I'm using Entity Framework and a SQL Server Database File
Say my solution is structured as such
MySolution
\MySolution.Data
\MySolution.Data\App_Data\MySolutionDB.mdf
\MySolution.BusinessLogic
\Presentation
The problem I am trying to solve is that I need to get a folder relative path to the database for the connection string because this project will not always be deployed in into the same folder structure, therefore it is imperative that the connection string is created dynamically based on the relative path.
Could someone offer some assistance on this. please?
P.S. I tried this, but it's not working:
string.Format("Data Source=(LocalDB)\v11.0;AttachDbFilename={0}\\MySolutionDB.mdf;Integrated Security=True", AppDomain.CurrentDomain.GetData("DataDirectory"))
EDIT: Getting this error message, which may be unrelated to the issue...
Connection to the database failed. The connection string is configured
with an invalid LocalDB server name. This may have been set in
'global.asax' by a pre-release version of MVC4. The default connection
factory is now set in web.config so the line in 'global.asax' starting
with 'Database.DefaultConnectionFactory = 'should be removed. See
http://go.microsoft.com/fwlink/?LinkId=243166 for details
Thanks to wdosanjos for pointing out my stupid mistake.
string.Format("Data Source=(LocalDB)\v11.0;AttachDbFilename={0}\\MySolutionDB.mdf;Integrated Security=True", AppDomain.CurrentDomain.GetData("DataDirectory"))
I did not escape \v11.0; it should have been \\v11.0;
Related
I am currently trying myself in Entity Framework in C# and trying to do the registration/auth with Identity. I was following this guide (3:38) but when came the migration part I've got some issues.
The person in the guide uses a PostgreSQL server on some hosting to connect to it with a connection string
Host=;Port=;Database=;Username=;Password;
and connects to his hosting. I don't have any hosting machine and never worked with servers. How can I use (if I actually can) a connection string to create a database file right in my project directory?
use connetion string :
"ConnectionStrings": {
"LocalhostConnection": "Host=127.0.0.1;Password=********;Persist Security Info=True;Username=databaseUser;Database=DatabaseName",
"RemoteConnection": "Host=IP or Domain Address;Port=3432;Password=********;Persist Security Info=True;Username=databaseUser;Database=DatabaseName"
},
mean of the host here (in the test environment) is the database (postgreSQL) installed on your computer. As foad abdollahi said, the host address can be IP address or Domain name or etc. so first you must find your PostgreSQL info installed PC. for retrive this info can use this link:PostgreSQL database service
The problem was that I didn't understand how the PostgreSQL work (and not sure that I understood it actually but I found a solution)
As abdollahi commented to the question I downloaded Postgres with pgadmin4 and followed another guide
.UseNpgsql("Host=localhost;Port=5432;Database=usersdb2;Username=postgres;Password=password");
Probably not the best connection string but I am happy it works :) Thanks
I have a C# ASP.Net MVC web application. I am trying to successfully connect to an Oracle database.
I am getting a "ORA-12514: TNS:listener does not currently know of service requested in connect descriptor" error.
I do not have access to the server the database is on. But I do have access to Oracle SQL Developer, which I have installed on my machine.
In my C# code I am setting the connection string like this:
ConnectionString = "DataSource=XXX.XX.XXX.XXX/abcd,1521;User ID=userid;Password=password;";
abcd should be the service name. and 1521 is the port number.
I understand that my connection string might not be the cause of the error, but I want to rule it out. Also, I know the more proper way of doing things is probably to set the connection string in web.config and retrieve it as needed, but I am doing it this way just for ease of testing until I know I am able to connect to the database successfully.
What is weird to me, is that I was able to connect to the database using Oracle SQL Developer using the same IP address, port number, service name, username, and password I am using in my connection string.
Primarily, I would like help knowing if my connection string looks valid. If you have additional thoughts about what the issue could be, that would also be appreciated.
using this command in Oracle SQL Developer:
select sys_context('userenv','service_name') from dual;
I am able to determine that the service name I am using in my connection string is one that exists, although I guess this does not guarantee that the service is up.
I am not a DBA by any means. In fact, I am still new to .Net and web development in general, but I have been assigned to troubleshoot this issue. Any help is appreciated.
I don't recall seeing the following format
DataSource=XXX.XX.XXX.XXX/abcd,1521
as valid (which doesn't mean its not, I've just not seen it).
The more common ones I've seen are:
DataSource=XXX
where XXX is a reference to your tnsnames.ora file
DataSource=//nnn.nnn.nnn.nnn/service_name
DataSource=//nnn.nnn.nnn.nnn:port/service_name
So maybe try those variants and see how you go. There's also more definitive list of alternatives at https://www.c-sharpcorner.com/UploadFile/nipuntomar/connection-strings-for-oracle/
I ended up figuring this out. My connection string format I don't t think was correct. I changed it to be:
ConnectionString = "DataSource=XXX.XX.XXX.XXX/abcd;User ID=userid;Password=password;";
Basically, I just took off the port number. In my case, the default port was what I needed anyway. Not sure what I would have done had I needed to specify the port number.
As new to Oracle I struggled a few days finding solution to this
this article helped me alot
As of Oracle 21 c
This is my Connection string for C#
Password=dev;Persist Security Info=True;User ID=Dev;Data Source=localhost:1521/XEPDB1
Keep in mind Dev is Username which is also the Schema name for Oracle
I'm doing my homework, a WCF service that uses SQL Server with Entity Framework, hosted through a console application, and using a WPF client.
There are 3 different projects, and the host and the service is in the same solution. I've included the Entity Framework connection string in the console hosts' app.config file from the web.config file from the service. This way the server and the host throw an exception when I try to make a query:
System.Data.Entity.Core.EntityException: 'The underlying provider failed on Open.'
The inner exception says:
SqlException: An attempt to attach an auto-named database for file C:\Users\username\source\repos\BlogAppWcf\BlogHost\bin\Debug\BlogDb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
So it basically searches for the .mdf file in it's own project folder, while it's inside the service's App_Data folder.
The original connection string looks like this, I copied this to the host's app.config from the web.config:
connectionString="metadata=res://*/BlogDbEntities.csdl|res://*/BlogDbEntities.ssdl|res://*/BlogDbEntities.msl;
provider=System.Data.SqlClient;
provider connection string="
data source=(LocalDB)\MSSQLLocalDB;
attachdbfilename=|DataDirectory|\BlogDb.mdf;
integrated security=True;
MultipleActiveResultSets=True;App=EntityFramework""
I've tried modifying the AttachDbFilename attribute in the app.config, I gave it an absolute path like this:
attachdbfilename=C:\Users\username\source\repos\BlogAppWcf\BlogAppWcf\App_Data\BlogDb.mdf;
and this way it works like a charm! No more exceptions on queries.
But this isn't the right way to do it, especially because I have to send it to my teacher. I want to give it a relative path, just like this:
attachdbfilename=..\..\..\BlogAppWcf\App_Data\BlogDb.mdf;
but it doesn't work this way.
Has anyone got any suggestions, maybe I'm doing or thinking something completely wrong?
According to your description and the issue you encountered, I think the problem boils down to the fact that the attached database is not properly attached to VS built-in database server instance. For this reason, I think we could configure the EntityFramework with VS built-in database instance string.
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MyStore;Integrated
Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
And then override the seed method of the DropCreateDatabaseAlways/DropCreateDatabaseIfModelChanges class to provide the seed data.
Feel free to let me know if there is anything I can help with.
Ok, so I'm doing a website in .Net and for one of my validators, I'm trying to connect to my database. It's a database that I created in my App_Data folder, so it's a local one. The thing is, I have the following on my C# file:
SqlConnection db = new SqlConnection();
db.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFileName=|DataDirectory|\baseDados.mdf;Integrated Security=True";
db.Open();
//MORE CODE
I've got an error on my ConnectionString. Can't I use the same connectionstring that the one in my web.config file? I have been looking to how to connect to my database, but none of the solutions worked for me 'till now. I'm probably overlooking something. Thanks. :)
|DataDirectory| is a pointer in the config that gets replaced by the actual location of the database. You are using an attached database, so it is looking for the actual directory the data file is located in.
My suggestion, as it is more likely to be like production, is attach the database file to the database server. Since it is .mdf, I am guessing SQL Server (99.9% sure it is SQL Server). You will then alter your database connection string to point to the server, database name, etc. The main change will be the center section. The other option is find the actual location of the file and attempt from there. This should work, as that is what the server does for you when it pulls from config.
I don't have time to look, but I bet there is something in config that points where that file is, or it is automatically stored in a specific location by the framework. A quick Google search should yield answers.
I have one solution with one project in it. This project is an asp.net mvc web application with xsockets.net websocket server (everything merged inside single project).
Everything was working for a few months, until today. Today I decided to update entity framework and xsockets.net. There were few errors on the way, but I solved almost all of them... almost.
Well, the part of my project that runs websocket server is not using correct connection string. I mean, I can login to my web application, and move around it (so asp.net mvc is using correct connection string), but my websocket server (which is using the same database) cannot gather any data from database, since it's throwing incorrect connection string exception.
And since everything is in the single project, with single web.config file, I don't know what to do next. I don't believe that this is websocket related error, maybe entity framework update has changed something? Anyways, is there any way to explicitly use connection string inside of a class? What else I can do to fix that?
When Entity Framework connects to create the entity objects it also establishes the connection string to that database. This usually isn't a problem since that project is referenced by another program that is overriding the server connection string with their own app config (or web config).
Typically in code when connecting to an instance of Sql Server, you write your code:
using ( MyServer context = new MyServer(myconfig.ConnectionStrings["MyServerName"]))
{
}
If you exclude providing he connection string when creating the instance of your context, you risk catching the default value created when you updated entity framework. So this probably answers both your questions: the why is it changed your connection string. The explicit use is the code example above.