SimpleMembershipProvider, Entity Framework and default database - asp.net

I'm using in a MVC4 internet app the new SimpleMemebership provider with Entity Framework code first. Evrything is fine except that the framework creates the new database with named "DefaultConnection" even if I changed it.
<add name="MyDB" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=BeerOperator; Integrated Security=SSPI; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
and in Filters\InitializeSimpleMembershipAttribute.cs
WebSecurity.InitializeDatabaseConnection("MyDB", "UserProfile", "UserId", "UserName", autoCreateTables: true);
I really don't understand what I need to change in order to have the User management table created into MyDB database.
Many thanks
davide

Nevermind, I found it.
In the AccountModel.cs I had:
public UsersContext() : base("DefaultConnection")
I changed into:
public UsersContext() : base("MyDB")
and now is ok.

Related

ASP.NET MVC identification tables creation

So I have a project with my custom, local DB (created by model-first approach). I need to create there identification tables (like asp_users, asp_roles, I don't remember how exactly they are called, but I hope you got the idea). As far as I know, they should be created on first registration, however it doesn't happen:
I can't see those tables in SQL Management Studio either.
My connection string (created automatically with DB):
<!--<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-WebApplication1-20170504122316.mdf;Initial Catalog=aspnet-WebApplication1-20170504122316;Integrated Security=True" providerName="System.Data.SqlClient" />-->
<add name="DefaultConnection" connectionString="metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=VADIM-PC;initial catalog=PIT_3_Project_DB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
The first connection string is truly default, the second is mine.
The fun part is - authentication works fine, I can register and login, and I don't see where my code cane use with the default local DB.
UPD: Sorry, I haven't changed this row:
public ApplicationDbContext()
: base("DBModelContainer", throwIfV1Schema: false)
{
}
I have changed DBModelContainer to DefaultConnection and now I am getting this error (when I am trying to register)
The entity type ApplicationUser is not part of the model for the current context.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
You should create these tables with code first migrations.
First step:
Uncomment first default connection string,rename it for example DefaultAuthConnection and modify it like this (for local DB).
<add name="DefaultAuthConnection" connectionString="data source=.;initial catalog=PIT_3_Project_DB;persist security info=True;" providerName="System.Data.SqlClient" />
<add name="DefaultConnection" connectionString="metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=VADIM-PC;initial catalog=PIT_3_Project_DB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Second Step: Open your IdentityModels.cs and modify ApplicationDBContext like this:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultAuthConnection", throwIfV1Schema: false)
{
}
}
Third Step: Open Package Manager Console (View->Other Windows->Package Manager Console) and write follow steps:
Enable-Migrations -ContextTypeName
WebApplication1.ApplicationDbContext
Add-Migration Init
Update-Database
From now on, you can see authentication tables in your local database.

Unable to find the requested .Net Framework Data Provider. It may not be installed

I am having problem in running my ASP.Net MVC project which is an admin project. It connects with a sql server database to fetch record. When I try to build and run, I am welcomed with this error: "Unable to find requested .Net Framework Data Provider. It may not be installed".
Here is the link to this error.
I have tried many solutions available on stackoverflow but none of them worked for me that's why I am posting this question here again. I tried changing the Target Framework version in Properties of project to all the available versions but all in vain. Here is the screenshot of my Global.asax.cs file which is causing this exception.
Below is the connection string of my project:
<add name="AlkhaleejEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Alkhaleej;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"/>
Connection string provided above indicates EF connection provider being used:
connectionString="metadata=res:///Models.Model1.csdl|res:///Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Alkhaleej;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"
Note that SimpleMembershipProvider can't use EF provider connection string (see this post) due to usage of SqlClient provider instead of EntityClient, hence it requires SQL Server connection string to interact with database.
Try open Server Explorer => Data Connections => right click your server connection, select Properties => add provided SQL Server connection string something like this one (leave EF connection string part as is, just add SqlClient provider connection string):
<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=Alkhaleej;Integrated Security=True" providerName="System.Data.SqlClient" />
Then, change connectionStringName parameter on WebSecurity.InitializeDatabaseConnection method inside SimpleMembershipInitializer class to SQL Server connection string name as given below:
public class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
// other code part
if (!WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "Email", autoCreateTables: true);
}
}
}
NB: The ideal setup for EF projects should include at least one SqlClient connection string and one EntityClient connection string, which may serve different providers with same target database.
Similar issues:
SimpleMembershipInitializer won't initialize
Unable to find the requested .Net Framework Data Provider. (SqlClient)
Can SimpleMembership and Entity Framework share a connection string?

ASP.NET MVC 4 - Application not accepting new connection string - AppHarbor Deploy Issue

I'm currently working on an ASP.NET MVC 4 project that is using Entity Framework 4.3 with a CodeFirst approach using simple POCO classes. Also, I'm using SQL Server Express as the development database.
After building my classes and setting the connection string, I ran my project and it generated a SQL Server Express database for me with no problems.
The problem though, is that I am trying to deploy to AppHarbor and I'm having an issue with the connection string. AppHarbor requires that you install SQL Server as an 'Add-On' and configure the connection string to have an alias that will inject their Sequilizer connection string into the project that you push from GitHub.
Here is their documentation on how this works: http://support.appharbor.com/kb/add-ons/using-sequelizer
I believe I have all of this setup correctly, but there seems to be a problem with how my app is reading the connection string.
Here is the development connection string that I am using on my local machine:
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-FranchiseManager-201275154247;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Here is what the AppHarbor Sequilizer connection string looks like:
<connectionStrings>
<add
name="DefaultConnection"
connectionString="Server=0691298f-d461-40cc-86d6-a089016ba88d.sqlserver.sequelizer.com;Database=<removed hash value>;User ID=<removed hash value>;Password=<removed hash value>;"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
The first connection - generated locally by my EF - works just fine. The second - created by Sequilizer - is not being read by my application.
However - I can connect to the Sequilizer database through SQL Server Management Studio. So it must be my app right?
In order to trouble shoot my deployment to AppHarbor, I hard-coded their connection string into my app instead of the one auto-generated by EF and tested on my local machine.
Here's what I did:
Replaced the connection string in Web.config with the one AppHarbor
provided,
Cleaned the solution,
Rebuilt the solution
But when I ran the application, it is still utilizing the original database generated by EF - which must mean that it is still reading the old connection string.
It seems like changing the connection string is not enough. What else in my application should I change in order to replace the connection string?
Any advice is appreciated - thanks!
EDIT
Here is my DbContext class:
public class FranchiseManagerContext : DbContext
{
public DbSet<FranchiseSet> FranchiseSets { get; set; }
public DbSet<Franchise> Franchises { get; set; }
}
This works as-is with the connection string named "DefaultConnection".
How does EF know to match the DbContext with the connection string in this scenario, but it cannot do it if you change the name of the string?
UPDATE
I think I know what it is now from this SO answer: What is the point of "Initial Catalog" in a SQL Server connection string?
It looks like the Initial Catalog attribute is specifying the particular database to be used when Entity Framework first kicked in.
You have to specify the name of the connectionstring you want your DbContext to load. It has no way to magically guess that you want it to use the one called DefaultConnection. There's a heuristic that says that if no name is specified, it'll look for for a connectionstring with name set to the name of the class that inherits from DbContext. Ie. if you have:
MyAwesomeDatebase : DbContext
... then Entity Framework will work out of the box with this:
<add name="MyAwesomeDatebase" connectionString="blah" providerName="System.Data.SqlClient" />
... but if you have:
<add name="DefaultConnection" connectionString="blah" providerName="System.Data.SqlClient" />
... then it won't work because Entity Framework has no way of knowing that MyAwesomeDatebase goes with DefaultConnection.
To make that work, do this:
public class MyAwesomeDatebase : DbContext
{
public MyAwesomeDatebase() : base("DefaultConnection")
}
... and you're golden.
Ok, I think I've finally got this working.
I can't find this anywhere in the AppHarbor documentation (perhaps it is something specific to .net mvc?), but the connection string must have the same name as my DbContext class.
I found some hints on this by looking at some other questions on SO.
For anyone else that may run into the same issue:
be sure the name attribute of the ConnectionString in Web.config is the same name as your DbContext Class
Commit and push the project to your repo
Make sure the Alias name on AppHarbor is the same name as your connection string
Deploy the new build on app harbor after step 3 (this is necessary to pick up the new connection string name)
After doing that my app picked up the Sequilizer database and it's now working fine.

Database Connection problem with MVC3

I am using MVC3 with Code first approach. In this case, I had to generate my entity classes from the existing databse.
The database was
Database1.mdf
Once I did that, it created DBEntities and added a new connectionstring in my Web.config which looked something like this:
<add name="DATABASE1Entities" connectionString="metadata=res://*/Models.Task.csdl|res://*/Models.Task.ssdl|res://*/Models.Task.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\DATABASE1.MDF;integrated security=True;user instance=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Now I removed DB Entities and came up with my own DB Context class.
and
Now, I am working with the following connectionstring:
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|DATABASE1.mdf;User Instance=true" providerName="System.Data.SqlClient" />
Name of my DBcontext class is TaskContext.
I am not sure what happeend afer this. My code works. But it works on some blank database and it does not reflect anydata in database.mdf. If I add something using my controller then I see that thing is added. But it does not get reflected in Databse1.mdf.
It seeems to have created a its own databse. But I do not see andy .sdf or .mdf file created anywhere.... I am not sure what is going on?
Make the name of your connection string same as TaskContext:
<add name="TaskContext"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|DATABASE1.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
OR, you can use your favorite connectionStringName by following these steps:
1- When you are creating a TaskContext object, changes it's connectionString:
var cn = WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
// or
var cn = WebConfigurationManager.ConnectionStrings[0].ConnectionString; // use your connection index instead of 0
var _context = new TaskContext();
_context.Database.Connection.ConnectionString = cn;
2- in your context class (TaskContext), you should tell to modelBuilder to
remove IncludeMetadataConvention
by this code:
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
base.OnModelCreating(modelBuilder);
}
Try making the name of your connection string and DBContext the same. I believe reading at some point that EF Code First employs a lot of conventions so if it doesn't find a connection string named as the DB Context (in your case "TaskContext") it will try to connect to a SQLExpress (whether or not there is one installed) and will try to find or create the database.
I'm assuming you've got SQLExpress installed. What's down in C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\? (I think that's the path) Have you got a DB sitting there for this project? Maybe something like [YourNamespace].TaskContext.dbf?

ASP.NET EFCodeFirst not using correct connection string

I am trying to publish a website using ASP.NET MVC3 EF and CODEFIRST with a SQL Server 2008 backend. On my local machine I was using a sql express db for development, but now that I am pushing live, I want to use my hosted production database. The problem is that when I try to run the application, it is still using my local db connection string. I have completely removed the old connection string from my web.config file and am using the <clear /> tag before creating the new connection string. I have also cleaned the solution and rebuilt, but somehow it is still connecting to the old db. What am I missing?
This is the new connection string:
<connectionStrings>
<clear />
<add name="CellularAutomataDBContext"
connectionString=" Server=XXX;
Database=CellularAutomata; User ID=XXX; Password=XXX; Trusted_Connection=False"
providerName="System.Data.SqlClient" />
</connectionStrings>
UPDATE
When I debug and look at the DBCONTEXT object, this is what is showing up for its connection:
Data Source=.\\SQLEXPRESS;Initial Catalog=CellularAutomata.Models.D1K2N3CARuleDBContext;Integrated Security=True;MultipleActiveResultSets=True"
I am unsure why this is happening because I cannot find it being set to this anywhere. Also, under configuration it says LazyLoadingEnabled = true, I assume this may be part of the problem, maybe it is not loading the new connection string. Where do I change these parameters?
UPDATE 2
EFCodeFirst is using a default connection string, I can't figure out how to get it to accept the connection string that I specify in the web.config file.
So, When using EF CodeFirst, there is a default connection string that it uses. If you want to be able to use a custom connection string, there are a few parameters guidelines that you must follow.
name ="this must match the name of your database context class"
connectionString="Server=yourserverurl; Database=yourdatabasename; User ID=youruserid;
Password=yourpassword; Initial Catalog=the name of the database to use;
Trusted_Connection=False"
providerName="System.Data.SqlClient"
So far this is working for me.
The connectionString you show is not an EF connection string. The EF won't use it. So you're changing the wrong thing.
An EF connectionString will include providerName="System.Data.EntityClient"
It will look for the same name as your context and depending on what else you
are using other names as well. I usually use the following for controlling
specific features with either the same or specific connection strings
(I keep app services in a different db for example so EFCF can drop tables as needed):
<connectionStrings>
<add name="MyAppContext" .../>
<add name="ApplicationServices" .../>
<add name="DefaultConnection" .../>
</connectionStrings>

Resources