Create user database via code first ASP.NET MVC - asp.net-mvc

I'm trying to use a MySQL database with asp.net MVC via a code first approach and I don't know how to create the tables, I thought it would create by itself.
I get the message : "Table 'XXX.aspnetusers' doesn't exist"
Do I need to run migrations or something like that?
Thanks

I got a little further by using update-database. You must have change your connection string and your provider to correspond to your MySql
Example :
<add name="DefaultConnection" connectionString="server=127.0.0.1;User Id=root;password=;database=myDB" providerName="MySql.Data.MySqlClient" />
Provider :
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
</providers>
</entityFramework>
You should also put this on your dbContext :
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
Thanks

Related

Using Effort with EF6 in a DB First approach

I'm using the Model First approach with EF6 and I'm trying to use Entity Framework Effort to develop in-memory tests.
Here is what I do in my test:
var inMemoryConnection = Effort.DbConnectionFactory.CreateTransient("name=MyEntities");
var inMemoryContext = new MyEntities(inMemoryConnection);
MyEntities:
public partial class MyEntities: DbContext
{
public MyEntities(DbConnection dbConnection)
: base(dbConnection, contextOwnsConnection: true)
{
}
When I run the tests, I get an error saying I didn't specify any [key] attributes which is normal since I am not using a Code First approach. Therefor, the OnModelCreating method is called and shouldn't have to.
Is there a way to use Effort in a Model First design without having to add these attributes?
Thanks !
I found my mistake.
Turns out Effort.DbConnectionFactory.CreateTransient is used for Code-First.
Instead if you're working with a .edmx, Model-First, it is Effort.EntityConnectionFactory.CreateTransient("name=MyEntities") you have to use.
I too had a bit of a difficult time in trying to get Effort to work with a DB first, or model first as it's also known, approach. This is what I did to make it work:
Download the Effort.EF6 nuget package
Add the effort.provider to the entity-framework config section:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="Effort.Provider" type="Effort.Provider.EffortProviderServices,Effort" />
</providers>
</entityFramework>
Replace the sql-provider with the Effort-provider in the connection-string:
<connectionStrings>
<add name="testDb" providerName="Effort.Provider" connectionString="metadata=res://*/StaginDB.csdl|res://*/StaginDB.ssdl|res://*/StaginDB.msl;provider=System.Data.SqlClient;provider connection string="data source=testDB;initial catalog=foobaroo;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" />
</connectionStrings>
If your model-first context doesn't offer a constructor you can inject a connection into, you can modify your tt-template to do so:
<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{
// I added this constructor so I could inject a db-connection into the context:
public <#=code.Escape(container)#>(System.Data.Common.DbConnection dbConnection, bool contextOwnsConnection)
: base(dbConnection, contextOwnsConnection)
{
}
// Original constructor
public <#=code.Escape(container)#>()
: base("name=<#=container.Name#>")
{
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
this.Configuration.LazyLoa.... etc. etc.
And we can now use that constructor to instantiate a connection, and an Effort-based in-memory db-context based on this connection:
System.Data.Common.DbConnection connection = Effort.EntityConnectionFactory.CreateTransient("name=KPDBSTAGINGEntities");
TestDbContext testDbContext = new testDbContext(connection, false);
TestDbContext.your-entity.add( new your-entity() { etc. tec. });
TestDbContext.SaveChanges();
Hope this helps.
P.S. Others have had to add a db-provider-factory section to their config. This was not required for me, but maybe for you:
<system.data>
<DbProviderFactories>
<add name="Effort.Provider" invariant="Effort.Provider" description="Effort.Provider" type="Effort.Provider.EffortProviderFactory,Effort" />
</DbProviderFactories>
</system.data>

way to set connection string for database migration in web.config

I have an ASP MVC 5 app with code first migrations enabled. Whenever I publish it to a server, it adds an extra connection string to the Web.Config file along with a "parameter" element, and it breaks the site until I replace it. It looks like:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
<contexts>
<context type="MyApp.DataLayer.MyContext, MyApp">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[MyApp.DataLayer.MyContext, MyApp], [MyApp.Migrations.Configuration, MyApp]], EntityFramework, PublicKeyToken=b77a5c561934e089">
<parameters>
<parameter value="MyContext_DatabasePublish" />
</parameters>
</databaseInitializer>
</context>
</contexts>
</entityFramework>
<connectionStrings>
<add name="MyContext" connectionString="Data Source=SQLServerName;Initial Catalog=MyDB;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
<add name="MyContext_DatabasePublish" connectionString="MyContext_DatabasePublish.ConnetionString" providerName="System.Data.SqlClient" />
</connectionStrings>
I presume that extra connection string is for the database migrations, is that right? All I have to do to get things working is replace the connection string with the one above it, so replace MyContext_DatabasePublish.ConnetionString with Data Source=SQLServerName;Initial Catalog=MyDB;Integrated Security=SSPI for example.
First, is that connection string even needed? This is all in dev, and my migrations were all done from my local machine.
If it is needed, is there a way to keep it from coming in as MyContext_DatabasePublish.ConnetionString and instead come in as the connection string that works so I don't have to manually replace it every time I publish an update?
Thank you in advance for any information and advice!
See post here:
https://blogs.msdn.microsoft.com/aspnetue/2012/06/12/deployment-in-visual-studio-2012-rc-using-entity-framework-code-first-migrations/
This occurs when you setup code first migrations so that you can define a privileged account to run your migrations without having to elevate the privileges of your normal context user.

Multiple EF6 DbContext for one DbConfiguration in ASP.NET 5

I'm trying to port my MVC 5 application to MVC 6. I'm using Devart dotConnect for MySql and Oracle. I have trouble configuring my application.
Right now I have the following entries:
<entityFramework>
<providers>
<provider invariantName="Devart.Data.MySql" type="Devart.Data.MySql.Entity.MySqlEntityProviderServices, Devart.Data.MySql.Entity" />
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="Devart.Data.MySql" />
<add name="dotConnect for MySQL" invariant="Devart.Data.MySql" description="Devart dotConnect for MySQL" type="Devart.Data.MySql.MySqlProviderFactory, Devart.Data.MySql" />
</DbProviderFactories>
</system.data>
My application have 3 DbContext classes (2x MySql, 1x Oracle) in separate assemblies, and I can only have 1 DbConfiguration class (Entity Framework 6 limitation).
If I set this configuration other contexts complain that they cannot see assembly with DbConfiguration class.
How do I get over that limitation?
I found myself in a similar situation the other day, and had to rely on web.config to enrich the configuration
<entityFramework codeConfigurationType="MyNamespace.MyDbConfiguration, MyAssembly">
...Your EF config...
</entityFramework>
Edit
The second option is to place DbConfigurationTypeAttribute on your context class
[DbConfigurationType(typeof(MyDbConfiguration))]
public class MyContextContext : DbContext
{
}
For more details check these resources
Ef6 docs: Code-Based Configuration Type (EF6 Onwards)
Ef6 docs: Moving DbConfiguration

Problems continuing a MVC project with Entity Famework

So I have to work on this project (ASP.NET MVC 4 with Umbraco) that uses Entity Framework and I think UmbracoMembeShipProvider.
Now I have to add Roles to the project. In the DB there's a Users table and some few others. There is no Identity/Roles or the sort in the DB. I tried to create a Roles table and a junction table between Users and Roles but then I couldn't update the models. I made an .edmx schema file and it didn't pick up the junction table, just the Roles table with all the columns pilled up from the junction table.
I tried to approach it by making a Roles entity in the .edmx file and then update the DB via migrations, that also didn't work because the project is stuctued in a way that is has a 'Core' project where all the models are and then a 'Web' project where some other models are. And it gave all heaps of errors.
In the Web project there's a 'Migrations' directory with 2 classes one of which has 2 empty methods (up/down) and one that creates some indexes and then a bunch of commented code.
I'm also quite a newbie in ORMs in general so I don't know how to approach this problem, continuing where the other devs, before me, left off.
In the meantime I'll pick up some tutorials about EF but any help or guidance will be really appreciated.
You need to include the necessary settings in your web.config file which references a connection string pointing to a database where the user/role tables exist. It should look something like this.
<membership defaultProvider="UmbracoMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add name="UmbracoMembershipProvider"
type="umbraco.providers.members.UmbracoMembershipProvider"
enablePasswordRetrieval="false"
enablePasswordReset="false"
requiresQuestionAndAnswer="false"
defaultMemberTypeAlias="Another Type"
passwordFormat="Hashed" />
<add name="UsersMembershipProvider"
type="umbraco.providers.UsersMembershipProvider"
enablePasswordRetrieval="false"
enablePasswordReset="false"
requiresQuestionAndAnswer="false"
passwordFormat="Hashed" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="UmbracoRoleProvider">
<providers>
<clear />
<add name="UmbracoRoleProvider" type="umbraco.providers.members.UmbracoRoleProvider" />
</providers>
</roleManager>
<roleManager enabled="true" defaultProvider="UmbracoRoleProvider">
<providers>
<clear />
<add name="UmbracoRoleProvider" type="umbraco.providers.members.UmbracoRoleProvider" />
</providers>
</roleManager>
<appSettings>
<add key="umbracoDbDSN" value="server=localhost;database=MSSM;user id=db_user;password=password" />

How do I setup ASP.NET Identity to use my own connection string?

I have an MVC5 app that's using EF. I would like to add ASP.NET Identity and I've noticed that the connection string for ASP.NET identity is using "DefaultConnection". What Do I need to do so that ASP.NET Identity tables are created in my already existing db (source=DILS-S1301;initial catalog=MVC5;) as specified in MVC5Entities and NOT DefaultConnection => (LocalDb)\v11.0??
thanks
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MySuperAwesomeMVCApp-20131105011429.mdf;Initial Catalog=aspnet-MySuperAwesomeMVCApp-20131105011429;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="MVC5Entities" connectionString="metadata=res://*/Models.Mvc5Model.csdl|res://*/Models.Mvc5Model.ssdl|res://*/Models.Mvc5Model.msl;provider=System.Data.SqlClient;provider connection string="data source=DILS-S1301;initial catalog=MVC5;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
I tried modifying "DefaultConnection" like so:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=DILS-S1301;AttachDbFilename=|DataDirectory|\MVC5.mdf;Initial Catalog=MVC5;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="MVC5Entities" connectionString="metadata=res://*/Models.Mvc5Model.csdl|res://*/Models.Mvc5Model.ssdl|res://*/Models.Mvc5Model.msl;provider=System.Data.SqlClient;provider connection string="data source=DILS-S1301;initial catalog=MVC5;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
but now i get an error:
Database 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\MVC5.mdf' already exists. Choose a different database name.
Cannot attach the file 'C:\Users\blah\Documents\Visual Studio 2013\Projects\MySuperAwesomeMVCApp\MySuperAwesomeMVCApp\App_Data\MVC5.mdf' as database 'MVC5'.
The actual question shall be "How do I setup ASP.NET Identity to use my own connection string?"
If above is the correct summary of your question, below is the answer.
ASP.NET Identity uses EntityFramework for database related tasks. So you can use following option as suitable.
Option 1: EntityFramework's default connection string can be setup using following code snippet in web.config
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
Option 2: Programatically, you can also pass ConnectionString name to the DbContext's constructor. like new ApplicationDbContext(MyConnectionString)
Actually all you have to do is change the DefaultConnection connectionString to be your desired connection string. If you used the normal settings for a new MVC 5 project, and the identity tables do not exist in the new DB they will be created there automatically.
You do not have to edit the portion of the connection string and you do not have to edit the DbContext constructor unless you want to change the conntectionString name and are not OK with replacing the default connection string.
If you are OK with replacing the default connection string, you should be able to just replace it... this worked for me.
I found this article helpful as well:
http://www.typecastexception.com/post/2013/10/27/Configuring-Db-Connection-and-Code-First-Migration-for-Identity-Accounts-in-ASPNET-MVC-5-and-Visual-Studio-2013.aspx

Resources