Can`t use Entity Framework - connection string not found - entity-framework

I am using VS2012 with .NET 4.5. I am learning Entity Framework and I have a problem. I added ADO.NET Entity Data Model to my project and generated my entities using the wizard.
The wizard added a connection string into app.config file :
<add name="MalariaEntities" connectionString="metadata=res://*/MalariaEntities.csdl|res://*/MalariaEntities.ssdl|res://*/MalariaEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=OFIR-PC;initial catalog=Malaria;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
In my project I am seeing all the entities and it seems fine but when I try to do any database action I get the following error:
No connection string named 'MalariaEntities' could be found in the application config file.
For example, I tried to insert simple row:
using (MalariaEntities DB_Context = new MalariaEntities())
{
MapsMainCategoriesDsc a = new MapsMainCategoriesDsc();
a.Category = "aa";
DB_Context.MapsMainCategoriesDsc.Add(a);
DB_Context.SaveChanges();
}
When the debugger reach to the last line the exception is raised. What can be the problem?
The wizard added a connection string so why my project cannot use it?
Thanks

Related

Code First connection string

I have an error:
An exception of type 'System.Data.Entity.Infrastructure.UnintentionalCodeFirstException' occurred in DataAccess.dll but was not handled in user code
Additional information: The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection.
In DataAccess project I have an EF 6 with App.Config file with string:
<connectionStrings> <add name="CVJobOnlineEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model 1.msl;provider=System.Data.SqlClient;provider connection string="data source=STEFAN-PC\SQLEXPRESS;initial catalog=CVJobOnline;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings>
and in my second project, which is the main Start-Up project I have in WebConfig:
<connectionStrings>
<add name="CVJobOnlineEntities"
providerName="System.Data.SqlClient"
connectionString="Server=.\SQLEXPRESS;Database=CVJobOnline;Integrated Security=True;"/>
So, obviously I am mixing EDMX and CodeFirst conn strings, but, I need it CodeFirst because of my Identity tables which I was incorporate in my SQL SERVER DB.
Also in my DbContext, I recalled base to use FirstCode (Model1.Context.cs):
public partial class CVJobOnlineEntities : DbContext
{
public CVJobOnlineEntities()
: base("name=CVJobOnlineEntities")
{
}
You must specify your connection string only once at the entry point of your application. Your DataAccess project does not need a connection string if it is not executable. Cut & paste the connection string from your DataAccess project to the web configuration file of your application entry point, overwriting the old one.
The problem was not exactly mixing two types of connection strings, since the one from DataAccess was never read by the Entity Framework. The one provided at your entry point config was just wrong in your scenario, because you are using model-first and not code-first.

Use Entity Framework Code first with any database

I use SQL Server developer edition and would like to use EF code first. I found many articles explaining how to work with either a localdb or SQLExpress. How do I tell my project to rather use my ..\SQL2008 instance?
I'm thinking that somewhere, somehow, one must be able to tell the project to use a specific connectionstring. But where? Adding it to my app.config file doesn't work. This is what I've tried:
<connectionStrings>
<add name="Context" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TimeApp;Data Source=Amanda-PC\SQL2008; MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
You can specify which connection string to use by passing the name of the connection string to the DbContext.
public class YourContext : DbContext
{
public YourContext()
: base("Context")
{
}
}
See this for more information

Exception with SimpleMembership and ADO.NET Entity Data Model

I create new ASP.NET MVC4 project with account controller uses forms authentification.
Then I run project and register new user for creating database file.
Then I create some tables in new mdf database file and I use ADO.NET Entity Data Model for this new tables instead of membership's tables.
After creating model.edmx there are two connection strings in web.config file.
name="Entities" connectionString="metadata=res://*/Models.Database.LAModel.csdl|res://*/Models.Database.LAModel.ssdl|res://*/Models.Database.LAModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDb)\v11.0;attachdbfilename=|DataDirectory|\aspnet-LAWebProject-db.mdf;initial catalog=aspnet-LAWebProject-db;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"
name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-LAWebProject-db;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-LAWebProject-db.mdf" providerName="System.Data.SqlClient"
The project debugs few times then crashed with following exception:
Can not connect to the database server SQL Server.
Please help me to resolve it...
Try removing that "\" from your connection strings:
|DataDirectory|\aspnet-LAWebProject-db.mdf;
becomes
|DataDirectory|aspnet-LAWebProject-db.mdf;
If it doesn't work, check that the db file aspnet-LAWebProject-db.mdf exists in the App_Data folder.
Make sure your LocalDb instance is running too:
LocalDB: Where is My Database?

Entity Framework DbContext Connection string in app.config/web.config not being seen

So, I have followed this instruction from ADO.NET team blog to try to make a small test project.
I have double-checked everything. It doesn't seem to work and keeps saying connection string is missing.
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx
Step. 1
Build this UserModels.dll. In the dll, App.Config file, edmx generated this connection string: (hit the 'test' button when making it, and it connects successfully, and generated the edmx diagram of all the tables from 'UserDatabase')
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="UserModelsContainer" connectionString="metadata=res://*/UserModels.csdl|res://*/UserModels.ssdl|res://*/UserModels.msl;provider=System.Data.SqlClient;provider connection string="data source=MyDesktop\SQL2008;initial catalog=UserDatabase;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Step 2.
Then I made a test project:
class UnitTetst1 ....
TestMethod1()....
using (var db = new UserModelsContainer()) {
int i = db.Users.Count(); // <---expecting '0' for a new db, but I get an exception
}
---------PROBLEM HERE -----------------
Step 3. Run the test. Then I get an error InvalidOperationException like this:
"No connection string named 'UserModelsContainer' could be found in the application config file."
Seems like DbContext doesn't know where to pick up the connectionStrings from App.Config??
Please help~~
When running a program, it's the app.config of the .exe file being run that is read. The app.config of the .dll is never used. Since UserModel.dll is a dll, there must be an .exe (or web site) somewhere that you run. Place the connection string in that exe's app.config (or if it is a web site in the web.config).
I had this issue when I was attempting to do an update-database command from the "package manger console". I had a separate project for my code first Data access layer and another for my web project, etc
I was using the following command: "update-database -projectname MYPROJECTDANAME -CONNECTIONSTRINGNAME CONNECTIONSTRING -Force"
so it pointed at my MYPROJECTDANAME project however it takes the connectionstring name from startup project you have specified. Therefore make sure the project you have marked as the startup project has the required connection string.

Setup of mvc-mini-profiler for EF-db- first

I'm trying to use the mini-profiler with old-style EF code - database-first.
So far:
I've created a db context using:
string connectionString = GetConnectionString();
var connection = new EntityConnection(connectionString);
var profiledConnection = ProfiledDbConnection.Get(connection);
_context = profiledConnection.CreateObjectContext<MyEntitiesType>();
but then I hit a "Unable to find the requested .Net Framework Data Provider. It may not be installed."
which I worked around using a <system.data> reference to the MvcMiniProfiler provider:
<system.data>
<DbProviderFactories>
<remove invariant="MvcMiniProfiler.Data.ProfiledDbProvider" />
<add name="MvcMiniProfiler.Data.ProfiledDbProvider" invariant="MvcMiniProfiler.Data.ProfiledDbProvider" description="MvcMiniProfiler.Data.ProfiledDbProvider" type="MvcMiniProfiler.Data.ProfiledDbProviderFactory, MvcMiniProfiler" />
</DbProviderFactories>
</system.data>
but now I'm hitting a stack overflow somewhere in C:\Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\Data\ProfiledDbProviderServices.cs. Looking at the latest source I'm wondering if I've somehow got the setup wrong for this - if somehow my profiled connection is containing another profiled connection is containing....
Any help/advice?
Update - looking at http://code.google.com/p/mvc-mini-profiler/wiki/FrequentlyAskedQuestions at least one other person has seen the same sort of problem with 1.7 - although (s)he's doing code first. I'll keep playing to see if I can work out what to do...
Try 1.9. With the update, I just added the new Initialize method in Application_Start and removed the DbProviderFactories config section and now I have SQL profiling with EF (2 databases even, one with code first and one with database first).
protected void Application_Start()
{
....other code
MiniProfilerEF.Initialize();
}