Conity Framework Console application connecting to the wrong database

I have the first EF code web application that works fine and connects correctly to the database server. I added a console application to the solution to check the logic for the service that will work with the application.

There was a head scraper about why the console application did not save data, so I reduced it to a simple selection from the database, and it turned out that the original console application saved the record, but to a different database than what is indicated in the connection string.

Here is the connection string from app.config:

<add name="DatabaseContext" connectionString="Data Source=xxx.xx.x.xx; Initial Catalog=OKWU_Gateway; User ID=xxxxx; Password=********; Trusted_Connection=False;" providerName="System.Data.SqlClient" /> <add name="DevelopmentEntities" connectionString="metadata=res://*/EntityModel.csdl|res://*/EntityModel.ssdl|res://*/EntityModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=;Data Source=|DataDirectory|\OKWU_Gateway.mdf" providerName="System.Data.EntityClient" /> 

Database:

Console application is very simple

  Database.SetInitializer<DatabaseContext>(null); static void Main(string[] args) { using (DatabaseContext db = new DatabaseContext()) { var query = from u in db.Users where u.Id == 1 select u; foreach (User u in query) { Console.WriteLine(u.Id + " " + u.FirstName + " " + u.LastName); } Console.ReadLine(); } } 

but instead of connecting to db on the remote server, it connects to sqlexpress on the dev machine and hits that database.

 UniversityGateway.Data.DatabaseContext 

I tried changing the connection string to indicate | DataDirectory | to the SQL connection string and it does not matter. The connection strings are the same as in web.config, and, as I said, the web application is working fine.

Any ideas on what I am missing, or point me in the right direction to solve this?

+6
source share
1 answer

OK, after a lot of digging, I found a solution. Not sure if this is the right / best one, but it works, so I can move on.

Since the console application did not comply with the connection string in app.config, I specified the connection in code using

 db.Database.Connection.ConnectionString 

I still feel like I'm missing something here.

Found that an additional part of my problem is that EF Codefirst does not work well with Sql Server 2005 DateTime data types.

0
source

Source: https://habr.com/ru/post/918253/


All Articles