How can I separate "Data" from my console application? - c#

I have two projects:
Console application
Class Library
I want the Class library to define the classes, create edmx files and to have a partial connection string, like:
<add name="BlogEntities" connectionString="metadata=res://*/Blog.csdl|res://*/Blog.ssdl|res://*/Blog.msl;provider=System.Data.SqlClient;provider connection string='{0}'" providerName="System.Data.EntityClient" />
I want my Class Library to define the csdl, ssdl and msl files. My Console application doesn't care about the metadata, it will only define the database, user and password.
How can I split the connection string in two like this?

from my memory, if you create the model in a class lib, VS will create an app.config in the lib project.
Simply merge the content of this file in the app.config of the console library.
in this scenario, you can have a "design" config in the app.config file of the lib, and a run time config in the app.config of the console application.

Create a class in your library (e.g. Connector) that allows you to provide whatever connection values you will need (database, user, password). Then use this class in your console application and provide the necessary values however you see fit.

I found out that I can name all entities with the same name, e.g. Entities. My app.config will need to be on the Console Application, but I can use a single ConnectionString.
<add name="Entities" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLExpress;Initial Catalog=Test;Persist Security Info=True;User ID=test;Password=test;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
The metadata can be set to res://*/ and it will work globally. From MSDN:
Model and mapping metadata used by the
Entity Framework is loaded into a
MetadataWorkspace. This metadata is
cached globally and is available to
other instances of ObjectContext in
the same application domain.
I can also force that any plug-able module will use a ConnectionString passing on the context constructor:
new Blogs.Data.Entities("name=Entities");

Related

EntityFramework through Class Library

I have a class library called DataManip, a webform project and a winform project.
DataManip is a class that will contain all the necessary methods to manipulate the database, including handling migrations and database updates.
The .mdf database is also inside the DataManip project.
The problem that I am having right now, is that when I setup a connection string in the App.config file of DataManip, it doesn't recognize the |DataDirectory| substitution string.
Connection string :
<add name="Context" connectionString="Data Source=(LocalDB\v11.0;AttachDbFilename=|DataDirectory|DB\mydatabase.mdf;Integrated Security=True providerName="System.Data.SqlClient" />
Harcoding the path in AttachDbFilename will successfully generate the database, but working with team members make this approach not possible.
The error message that I get when I try to run update-database in DataManip is :
A file activation error occured. The physical file name '\DB\mydatabase.mdf' may be incorrect...
How can I get the DataDirectory substitution string to work in a class library?

No connection string named could be found in the application config file

I'm using EF and generated .EDMX from it but then I only wanted it to be used for automated generation of Class Files.
I then used the Class Files to create a Entity Model and then created a DB Context and then Repository. I'm calling a WebApi (which is in a separate project but same solution) to access the repository to GET data. While I run the WebApi, I'm getting the error,
{"No connection string named 'DBEntities' could be found in the application config file."}
But within my DAL, I have a webConfig and that has the following entry so I'm not quite sure what has gone wrong,
add name="DBEntities" connectionString="metadata=res://*/Models.DBModel.csdl|res://*/Models.DBModel.ssdl|res://*/Models.DBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MY-PC;initial catalog=DB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient"
In the DBContext file, remove
public RaficaDB()
: base("name=DefaultConnection"){}
to
public RaficaDB()
: base("DefaultConnection"){}
EF 4.3, EF 5 and EF 6 do not like the connection string being called name=xxxxx
Answer found here -> No connection string named 'MyApplicationEntities' could be found in the application config file
You say "within my DAL, I have a webConfig". I guess the connection string is in the configuration file of a referenced class library, but not in the main configuration file you have in your entry project (a web api project, I guess looking at the tags).
If so, just copy the connection string in the entry project configuration file.
Insert following section in the configuration section of the .config file of the same project where your .edmx file is under.
You may also create different connection string for different environment in the .config file of the main project and pass any of the connection string as parameter of the constructor of the DBContext.
<connectionStrings>
<add name="DBEntities" connectionString="metadata=res://*/Models.DBModel.csdl|res://*/Models.DBModel.ssdl|res://*/Models.DBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MY-PC;initial catalog=DB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
Setting the project as Startup project worked for me
I found that this worked:
1) Check if you have several "App.config" files.
2) Check if has a wrong name than the connection string it has to use.
3) Save the project and run the program
It should work now.
Copy and paste the connectionstring to your WEBAPI Project web.config file will solve the issue.
It's dumb, but I had this error that was fixed by a Rebuild All !!
Might as well have turned it off and on again....
If none of the above fixes the issue, then probably you are doing the mistake I did, here was my case:
I have multiple projects in my solution and the Startup project was different than the one having the entity framework, switching project from the package manager console seems like a buggy thing especially in entity framework commands, so here what I did:
Set your webapi(Or the project has the entity framework) as a startup project.
Rebuild the solution and try again.
Run the entity framework command again.
If the above doesn't work then try to close the solution and try from Step 2, this should fix it.
The easiest solution:
Remove current edmx file and related connection string in app.config
and add Edmx item with same name as previous again.
this worked for me.

Not using database connection string

I have google'd the crap out of this problem, I cannot find a solution.
Using EF code first approach against a domain assembly, being consumed by a .net web application.
in the domain project there is a app.config, in there I have the following connection string for EF
<connectionStrings>
<add name="DefaultConnection" connectionString="Initial Catalog=easyDayTea;Data Source=localhost;user=sa; password=12344321" providerName="System.Data.SqlClient" />
Then in the context class TeaDb.cs I have the following constructor:
public TeaDb()
: base("name=DefaultConnection")
{
}
I have also tried just using "DefaultConnection" by itself in the constructor.
The problem:
Everything was fine until EF decided it wasn't going to take notice of additional classes/tables added to the context, so I removed EF from the project by deleting the migrations folder and empting the database of tables, then re ran enable-migrations and then the web application project to make EF do it's stuff to the database. However it did nothing!
When I run the web application though it works! and there is data (from the seed) in the tables, however not in any database i can see! It must be using a portable sql file, which doesn't make sense as I have it configured for a specific database / server by use of the configuration string.
I have also tried specifically specifying the connection string to use by doing a:
update-database -ConnectionStringName DefaultConnection -f
Still no joy.
If anyone could help me it would be amazing!
Thanks,
Xavier.
You'll find your database at Users\[youruser]\[Name you passed in your context constructor].mdf
app/web.config are only used if they are in the main project, if you have an app.config/web.config outside your main project it will not be used (some templates add them, but they are meant to be used as an example).
Check this answer for a similar problem with EF4
EF doesn't use the connection string from the app.config in the class library. It will use the connection string from the web.config in your web application. If you don't have the connection string defined in your web.config then it might be using conventions to attach the database with LocalDb in your App_Data directory.

No connection string named 'MyEntities' could be found in the application config file

I am using entity framework and ASP.NET MVC 4 to build an application
My solution is split into two projects;
A class library that includes my data model (.edmx) file and a few custom interfaces
The 'container' MVC project that references the class library above
My problem is that when I attempt to use the 'MyEntites' DbContext I get the the following error:
No connection string named 'MyEntities' could be found in the
application config file.
I guess the problem has something to do with the fact that connection string lies within the app.config of the class library rather than the MVC project.
Does anyone have any suggestions?
Try copying the connections string to the .config file in the MVC project.
You are right, this happens because the class library (where the .edmx file) is not your startup / main project.
You'll need to copy the connection string to the main project config file.
Incase your startup / main project does not have a config file (like it was in my Console Application case) just add one (Startup project - Add New Item -> Application Configuration File).
More relevant information can be found here:
MetadataException: Unable to load the specified metadata resource
make sure that you make your project (with the DbContext) as startup
OR
Add to the project that is set as startup your connection string in the app.config (or web.config)
OR
Call the command like this
Update-Database -Script -ProjectName '<project name>' -StartupProjectName '<project name>' -ConnectionString 'data source=.;initial catalog=<db name>;integrated security=True;MultipleActiveResultSets=True' -ConnectionProviderName 'System.Data.SqlClient'
Then try again
You could just pass the connection string to EntityFramework and get on with your life:
public partial class UtilityContext : DbContext
{
static UtilityContext()
{
Database.SetInitializer<UtilityContext>(null);
}
public UtilityContext()
: base("Data Source=SERVER;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD;MultipleActiveResultSets=True")
{
}
// DbSet, OnModelCreating, etc...
}
copy connection string to app.config or web.config file in the project which has set to "Set as StartUp Project" and if in the case of using entity framework in data layer project - please install entity framework nuget in main project.
As you surmise, it is to do with the connection string being in app.config of the class library.
Copy the entry from the class app.config to the container's app.config or web.config file
If you have multiple projects in solution, then setUp project as started where you have your truth App.config.
Add an App.Config file
Set the project as startup project.
Make sure you add the connection strings after entityFramework section:
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</configSections>
<connectionStrings>
<!-- your connection string goes here, after configSection -->
</connectionString>
It is because your context class is being inherited from DbContext. I guess your ctor is like this:
public MyEntities()
: base("name=MyEntities")
name=... should be changed to your connectionString's name
It also happens if the startup project is changed to the one, which does not have the connection strings.
Right Click Solution - click properties
Under Common Properties,select startup project
On the right pane select the project which
has the connection strings (in most cases, it will be MVC projects -
the project that starts the solution)
Yeah, it's silly. You can avoid copying the connection string by using a connection builder. VB.Net code (used in production, but slightly modified here, so treat as untested, happy to assist with any issues), where I have a serverName variable, a databaseName variable, I pass them into a method and have it generate the connection for me:
Dim EfBuilder As New System.Data.EntityClient.EntityConnectionStringBuilder("metadata=res://*/VMware.VmEf.csdl|res://*/VMware.VmEf.ssdl|res://*/VMware.VmEf.msl;provider=System.Data.SqlClient;provider connection string=""data source=none;initial catalog=none;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""")
Dim SqlBuilder As New Data.SqlClient.SqlConnectionStringBuilder(EfBuilder.ProviderConnectionString)
SqlBuilder.DataSource = serverName
SqlBuilder.InitialCatalog = databaseName
EfBuilder.ProviderConnectionString = SqlBuilder.ConnectionString
Using vmCtx As New VmEfConn(EfBuilder.ConnectionString)
are you using more than one project on your solution?
Because if you are, the web config you must check is the one on the same project as de .edmx file
Add ConnectionString to MVC Project Web.config file
I've had this problem when I use multiple proyects, the start proyect with web.config and app.config for EntityFramework project.
for avoid this problem you must:
You need the connection string in the started *.config file.
You need have installed the EntityFramework DLL into your references
I have faced the same issue. I was missed to put connection string to startup project as I am performing data access operation from other layer. also if you don't have app.config in your startup project then add app.config file and then add a connection string to that config file.
I got this by not having the project set as startup, as indicated by another answer. My contribution to this - when doing Add-Migrations and Update-Database, specify the startup project as part of the command in Nuget Package Manager Console (do not include the '[' or ']' characters, that's just to show you that you need to change the text located there to your project name):
Enable-Migrations
Add-Migrations -StartupProject [your project name that contains the data context class]
Update-Database -StartupProject [same project name as above]
That should do it.
The connection string generated by the project containing the .edmx file generates the connection string, this would appear to be a holdover from the app.config sorts of files that were copied to the output directory and referenced by the executable to store runtime config information.
This breaks in the web project as there is no automatic process to add random .config information into the web.config file for the web project.
Easiest is to copy the connection string from the config file to the connections section of the web.config file and disregard the config file contents.
The best way I just found to address this is to temporarily set that project (most likely a class library) to the startup project. This forces the package manager console to use that project as it's config source. part of the reason it is set up this way is because of the top down model that th econfig files usually follow. The rule of thumb is that the project that is closest to the client (MVC application for instance) is the web.config or app.config that will be used.
Make sure you've placed the connection string in the startup project's ROOT web.config.
I know I'm kinda stating the obvious here, but it happened to me too - though I already HAD the connection string in my MVC project's Web.Config (the .edmx file was placed at a different, class library project) and I couldn't figure out why I keep getting an exception...
Long story short, I copied the connection string to the Views\Web.Config by mistake, in a strange combination of tiredness and not-scrolling-to-the-bottom-of-the-solution-explorer scenario.
Yeah, these things happen to veteran developers as well :)
This problem happen when you are using Layers in your Project and defined or install Entity frame work in DataLayer and try to run your Project
So to overcome from this problem copy the connection string from the layer where the Edmx file is there and paste the connection string in main web.config.
Add a connection string in the root web.config file of 'container' MVC project that references the class library as following:
<connectionStrings>
<add name="MyEntities" connectionString="complete connection string here" providerName="System.Data.SqlClient" />
</connectionStrings>
If you do not want to use "MyEntities" as connection name then change it as you wish but make the following change in your MyEntities DbContext class:
MyEntities: DbContext
{
public MyEntities():base("Name-Of-connection-string-you wish to connect"){ }
}
Reason for this error is, If we will not specify the name of connection string Or connect string in derived class of DbConext(In your case it is MyEntities) then DbContext will automatically search for a connection string in root web.config file whoes name is same as derived class name (In your case it is My Entities).
I had this problem when running MSTest. I could not get it to work without the "noisolation" flag.
Hopefully this helps someone. Cost me a lot of time to figure that out. Everything ran fine from the IDE. Something weird about the Entity Framework in this context.
Regular migrations
There are two options - the first one that everyone here has suggested is to ensure that the connection string is in the Web.config file of the project. When working with connection strings from Azure application settings, that means overwriting your Web.config values with the Azure values.
Azure or automatic migrations (programmatic)
There's a second option available if you're running migrations programmatically, that allows you to run migrations using a connection string that's obtained dynamically (or via Azure application settings) without storing it in Web.config:
When setting the configuration's TargetDatabase, use the DbConnectionInfo constructor that takes a connection string and a provider name instead of the constructor that takes just a connection name. If your connection string doesn't have a provider name and you're using SQL Server / Azure SQL then use "System.Data.SqlClient"
This could also result in not enough dll references being referenced in the calling code. A small clumsy hack could save your day.
I was following the DB First approach and had created the EDMX file in the DAL Class library project, and this was having reference to the BAL Class library, which in turn was referenced by a WCF service.
Since I was getting this error in the BAL, I had tried the above mentioned method to copy the config details from the App.config of the DAL project, but didn't solve. Ultimately with the tip of a friend I just added a dummy EDMX file to the WCF project (with relevant DB Connectivity etc), so it imported everything necessary, and then I just deleted the EDMX file, and it just got rid of the issue with a clean build.
There is a comment on the top answer by #RyanMann that suggests:
Store your connection strings in one config file, then reference them in other projects by <connectionString configSource="../ProjectDir/SharedConnections.config" />
This is a fantastic suggestion!
It also works to share connection strings between App.config and Web.config files!
Anyone wanting to follow this suggestion, should head on over to this SO answer.
It has a really great step-by-step guide on sharing connection strings among multiple projects in a solution.
The only caveat is that configSource must exist in the same directory or a sub-directory. The link above explains how to use "Add as Link" to get around this.
I had this error when attempting to use EF within an AutoCAD plugin. CAD plugins get the connection string from the acad.exe.config file. Add the connect string as mentioned above to the acad config file and it works.
Credit goes to Norman.Yuan from ADN.Network.
If you are using an MVVM model, try to copy the connection strings to all parts of your project.
For example, if your solution contains two projects, the class library project and the wpf project, you must copy the connection strings of the backend project (library class porject) and place a copy in the App.config file of the wpf project.
<connectionStrings>
<add name="DBEntities" ... />
</connectionStrings>
Hope it's helpful for you :)
Add Connectoinstrnig in web.config file
<ConnectionStiring> <add name="dbName" Connectionstring=" include provider name too" ></ConnectionStiring>

WebService doesn't read web.config

I've got 3 connectionstrings in web.config, and I used theirs like this:
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SomeName"].ConnectionString))
Every metgod is called by winforms application.
One of webmethods doesn't work properly because it reads only one connectionString:
data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
It's not a connectionString from my web.config .
I invoke every method in the same way.
How it's impossible ??
EDITED:
I use facade: This is structure:
WinForms calls WebMethod SaveItem
SaveItem calls method on Facade: SaveItemAndDoDatabaseStuff
SaveItemAndDoDatabaseStuff does database stuff.
We can't see your web structure, but is it possible that your app isn't configured as an application in IIS, therefore is picking up the master web.config? Which would look exactly like that...
Go into IIS and ensure it is an application (it may have a cog icon).
If your WinForms application talks directly to database X (not via the web service), then the connection string for database X should be in app.config (in the WinForms project).
If your Web Service (as I understand, this includes your facade and your database layer), talks to databases X, Y and Z, then the connection strings for X, Y, and Z need to be in web.config (in the Web Services Project).
It's using the default connection string asp.net has (in the machine.config in the .net installation folders).
Do a clear:
<configuration>
<connectionStrings>
<clear/>
... your connection strings here
</connectionStrings>
</configuration>
Btw, when you say you are using "SomeName" in the connection string. It isn't surely any random connection string you used, its the default: "LocalSqlServer".
You should store the connection-strings in the web.config or app.config in whatever project that you are executing.
In your case, you should have the connection-strings in your app.config for your winforms application.
Why not just add a Trace line to print out the configuration file being used just before you ask for the connection string. Simply add the following line:
System.Diagnostics.Trace.WriteLine(
System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile,
"APP_CONFIG");
Set a breakpoint after this and look at the Output window for a line that starts with "APP_CONFIG:". This will give the full path to the configuration file and allow you to determine where it's being loaded. If you still see a discrepancy between the runtime values and the configuration file then likely something is changing those values at runtime within your application.
This is a late answer, but perhaps worthwhile.
I have a web-service project, and I want to run it in two modes.
One is "local as app" (for testing), and for that, at least in my current system setup, the file where it reads from is
Web.config (which it apparently reads in deug mode INSTEAD of Web.Debug.config, at least for database configuration)
So, one replace the attribute section with and copy in the ones you would use in the "Calling project for hte web service).
So replace
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
with
<appSettings>
<!-- Database Connection -->
<add key="AppDatabase" value="RedactedDatabase"/>
<add key="AppLoginID" value="RedactedLoginID"/>
<add key="AppLoginPwd" value="RedactedPwd"/>
</appSettings>
The above are found in app.config in the "calling project".... To me, this is more elegant anyway.
Now it will work in both modes.
One could use a conditional compile in the C#, but now you just read it in:
C# code:
String whichDatabase = System.Configuration.ConfigurationManager.AppSettings["AppDatabase"];
String appUsedID = System.Configuration.ConfigurationManager.AppSettings["AppLoginID"];
String appUsedPwd = System.Configuration.ConfigurationManager.AppSettings["AppLoginPwd"];
The above works in either mode, without conditional compile directives.

Categories

Resources