Compiler error using EF4 as a separate project than my MVC project - asp.net-mvc-2

I'm trying to follow the general consensus that it's best to put one's domain objects in a separate project than their MVC project, but am getting the following compiler error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
Source File: C:\Users\Kevin\documents\visual studio 2010\Projects\HandiGamer\HandiGamer.Domain\Entities\HGDomainModel.Designer.cs Line: 44
Line 42: /// Initializes a new HGEntities object using the connection string found in the 'HGEntities' section of the application configuration file.
Line 43: /// </summary>
Line 44: public HGEntities() : base("name=HGEntities", "HGEntities")
Line 45: {
Line 46: this.ContextOptions.LazyLoadingEnabled = true;
I'm a bit confused, as HGEntities is there in the entity's App.Config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="HGEntities" connectionString="metadata=res://*/Entities.HGDomainModel.csdl|res://*/Entities.HGDomainModel.ssdl|res://*/Entities.HGDomainModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\HandiGamer.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Do I need to add the connection to my MVC Web.Config or something?

Yes you need to add it to your MVC Web.Config file.
Since you have an ASP.Net MVC project in place, the connection string must be present in the web.config of your MVC project where the runtime will be looking to find it. Basically any connection string should be in the config file of your executable project (i.e. where the .Net threads started from by CLR). So just copy and paste the whole connection string into your web.conig and you're done!

Related

Single Connection String with Multiple Entity Framework Models(Data First)

I have 3 different project having their respective EF entity data model pointing to same database.I don't want to save connection string in each of these project's app.config file but want to share it between my models.
I see this link on stackoverflow How to share a connection string between multiple entity data model.
But the problem with it is if I will update the EF model it will overwrite the code in EF Model's context and it will inherit from DbContext not from BaseContext.
Please help how can I resolve this.
You have to move your connection string in a separate config file:
ConnectionStrings.config
<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
<add name="connectionString"
connectionString="Integrated Security=SSPI; Persist Security Info=False; Initial Catalog=DbName; Data Source=.\SQLExpress;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Modify the connection string so that fit your requirement.
Then you can share it with all your projects like that:
1) Open your App.config (This file found in your project)
2) Add this line code somewhere behind </configSections>
...
<connectionStrings configSource="ConnectionStrings.config"/>
...
The trick in configSource:
"Gets or sets the name of the include file in which the associated configuration section is defined, if such a file exists."
https://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource(v=vs.110).aspx
What will happened:
ConnectionStrings.config must be first copied
All YourApplicationName.config will reference the shared connection string config file.
If the project does not have any App.config then just add it! or you can also loaded manually with ConfigurationSettings.
This is the best way to share the database configuration between the app.configs and when you change for example the Sql Server name, then you have only to modify the ConnectionStrings.config and not all App.configs!
It resolved as connection string always picked from MVC project and all other class library projects are referencing it automatically.

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.

Using ASP.NET Identity on MVC 5 project but httpcontext User.ProviderName is "AspNetSqlRoleProvider"

I have a MVC 5 project using ASP.NET Identity (Invidual user account). As Database ORM I am using Entity framework 6 and IoC is taken care by Ninject.
Solution structure is following
MVC project
-- has my controllers, views and ninject setup. For Ninject I got Ninject.MVC3 from nuget.
Data project
--- has my DataContext (IdentityDbContext) and my ApplicationUser (IdentityUser). My
Data services and all repositories
Core project
-- has all my entities and interfaces
[Authorize] attribute works fine and I have to login to access tha annotated action, but when I set [Authorize(Roles = "Admin")] I get
Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'.
I created my on CustomAuthorize attibute which was basically a copy of Authorize and noticed that the
httpcontext in protected virtual bool AuthorizeCore(HttpContextBase httpContext) User.ProviderName is "AspNetSqlRoleProvider".
So I added Rolemanages clear to my web.config. This resulted in
Configuration Error Description: An error occurred during the
processing of a configuration file required to service this request.
Please review the specific error details below and modify your
configuration file appropriately.
Parser Error Message: Default Role Provider could not be found.
Source Error:
Line 53: --> Line 54: Line 55: Line
56: Line 57:
Source File:
...myproject\WebUI\web.config
Line: 55
So whats the deal here? How can I set the Default Role Provider to use ASP.NET Identity?
So right after I posted the question I figured the answer. I had to add
<system.webServer>
<modules>
...
<remove name="RoleManager" />
</modules>
</system.webServer>
That did it. But there still is a question of why?

multiple applications single config file

I'm trying to write a service and configuration application. VB/C++ 2010 I've had a number of hits on google but they largely seem to be obsolete. What I have so far is a project with a single form app and a service app. The single form app has an "app.config" file and I have added a section:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="settings.config">
</appSettings>
</configuration>
In the Solution I have added a "settings.config" file and its contents is:
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="Setting1" value="This is Setting 1 from settings.config" />
<add key="Setting2" value="This is Setting 2 from settings.config" />
<add key="ConnectionString" value="ConnectString from settings.confg" />
</appSettings>
I have added a reference to then C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\System.Configuration.dll
library in both the forms app and the service app
In the very simple forms app i have the following code
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim s As String = _
System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
TextBox1.Text = s
End Sub
It doesn't work! Now clearly I am missing something. Its probably very simple. But my limited understanding is that this is automatically configuered by the config files I have? MS in their usual helful fashion seem to only give samples for 2012 and net 4.5 or greater. I need this to work on a 2003 server (as well) so I'm limited to net 4.0
The problem here is that the line System.Configuration.ConfigurationManager.AppSettings("ConnectionString") is looking for the key ConnectionString in your application's app.config file.
The fact that you have included that file key in your app.config file doesn't magically tell the ConfigurationManager to load the settings from a different file. If that's what you want you will have to read the setting for the file key and then manually load the configuration from that file.
This has not changed since the early versions of .Net though so I'm not sure why you were conflicted by the examples.
Add reference on existing assembly in .Net section of your Add Reference Popup
But i suggest you to use connectionStrings section in your config file
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

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.