MVC project not creating database - asp.net-mvc

Situation
MVC5 EF Code-First project
Database migrations enabled
Database in App_Data is not checked in via sourcecontrol
Connectionstring points to non existing database
Problem
When someone starts the project the database isn't created according to the connectionstring
My solution
Edit the webconfig dbcontext connectionstring and modify the initial catalog string and now it recreates the the database.
Gut feeling
This doesn't feel right. Isn't there another whay to do this that doesn't make my skin crawl like my own solution.
Thanx for any ideas.

Create your own DbConfiguration
public class MyDbConfiguration : DbConfiguration
{
public MyDbConfiguration()
{
SetDatabaseInitializer<MyDbContext>(new CreateDatabaseIfNotExists<MyDbContext>());
}
}
And then Add attribute to your DbContext
[DbConfigurationType(typeof(MyDbConfiguration))]
public class MyDbContext : DbContext
{
}
For more information about DbConfiguration please check here

Related

Use the same database for both my custom entities and identity context?

I want to make an MVC website with user logins/authentication etc.
I'm using EF CodeFirst to create my database.
If I create a new MVC project and select Authentication: Individual User Accounts, it will create a new project with an already existing IdentityDbContext etc.
Am I meant to continue using this along with my own DbContext? One context for my projects entities, and the other context for the Identity entities? Does this mean I'll have two separate databases, or can I give them both the same connection string?
I know this may be an open ended question, but are there any good resources/tutorials for AspNet Identity?
So far I've only been finding resources about AspNet Identity itself, and not how to integrate it with the rest of the project/database
You can specify the same connection string for both of your custom models context and identity context, all you have to do is to change the connection string in the constructor of the ApplicationDbContext class that resides in IdentityModels.cs file like so:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("YouCustomConnectionString", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
and the tables needed for identity will be created in the same database as your other entities, as for resource there is a good set of articles on identity here.

Enable Migrations in Multi-Tier MVC Application

I am creating a new application using MVC 5 (Razor Views), Entity Framework 6 (Code First), ASP.Net Identity 2.0 and Web API. Trying to create a decent de-coupled architecture, I wanted to enable migrations in my data layer, but I have a misunderstanding of how migrations work. Here's my basic solution architecture:
MyApplication Solution
|-Domain Project
|-Entity1
|-Entity2
|-Entity3
|-Data Layer Project (References Domain Project)
|-DbContext (Inherits from IdentityDbContext)
|-Migrations Folder
|-Service Layer Project (Web API)
|-Business Layer Project
|-MVC Project
|-Views
As shown above, the Data Layer Project I have enabled migrations by executing the Enable-Migrations command in the Package Manager Console. The problem is, it only scripts the models related to Identity (AspNetUserRoles, AspNetUserLogins, etc.). How does a migration know to include an entity? I need it to script the models in my Domain project and not quite sure how to tell EF/Migrations to do so.
UPDATE:
Per a request, my simple (out-of-the-box via scaffolded by new project) DbContext class below:
public class MyDbContext : IdentityDbContext<ApplicationUser>
{
public MyDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static MyDbContext Create()
{
return new MyDbContext();
}
}
The problem is, it only scripts the models related to Identity
(AspNetUserRoles, AspNetUserLogins, etc.). How does a migration know
to include an entity?
The migration "knows" what to script as it scripts on a per context basis. Look at the Configuration.cs class in the Migrations folder and you will notice that it is a generic class with the DbContext type passed in as follows:
internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
So it "knows" because you're explicitly telling it by passing in a MyDbContext generic type parameter.
So if you want to add your own entities classes for migration then you should have a DbSet for each of the entities in your DbContext. i.e.
public class MyDbContext : IdentityDbContext<ApplicationUser> {
public DbSet<Entity1> Entity1s {get;set;}
public MyDbContext()
: base("DefaultConnection", throwIfV1Schema: false){}
public static MyDbContext Create()
{
return new MyDbContext();
} }
If you don't want to reuse MyDbContext for your custom entites then you can create another context, and add your entity DbSets to that. But then you will have to explicitly enable and update the migrations as per How do I enable EF migrations for multiple contexts to separate databases?

EF4 database first configurable schema

I have one issue I am trying to resolve for days now, but I can’t get the right approach.
I am using EF4 and I have one application where I use DataBase First, which originally created the ObjectContext, and I donwloaded the DbContext generator and generated it.
The thing is, I need the application to be able to get the database SCHEMA from some configuration file, instead of ALWAYS using the “dbo” default.
I was trying to use the “ToTable” method (so I can specify the schema) in the “OnModelCreating” overload method but as this article sais, as I am using DataBase First, that method is not called.
How can I make the schema name configurable?
Is that even possible?
I read this article too, where it says I can combine database first with code first but I can’t see how to do that if I can’t use the "OnModelCreating" method.
Thanks a lot in advance!!!
I don't know about configuring schema. However if you want your db first approach to changed to the code first, just change the string parameter of your DbContext constructor.
Suppose that you have the following DbContext that EF Db first created for you:
public class MyDbContext : DbContext
{
public MyDbContext()
: base("Name=DefaultConnection")
{
}
// DbSets ...
}
change that to the following to start using code first and all magic tools of it (migration, etc.):
public class MyDbContext : DbContext
{
public MyDbContext()
: base("YourDbFileName")
{
}
// DbSets ...
}
It causes that EF creates a new connection string using SQL Express on your local machine in your web.config file with the name YourDbFileName, something just like the early DefaultConnection Db first created.
All you may need to continue your way, is that edit the YourDbFileName ConStr according to your server and other options.

Entity Framework 5 multiple databases

I am totally new to developing technology ASP.NET MVC + Entity Framework 4 5 (DataBase First). I'm in a problem that even after hours of research I have not found a solution.
On my application need that each client has their own database, which will be selected after login.
Create a mapping (edmx) for each base? I have to change the DbContext or connection string lasts execution?
I have no idea where to start.
Can I create a mapping (edmx) for each database and change DbContext or connection string in runtime?
Thanks All.
When you're creating your DbContext you can just pass in the name of connectionstring in your web.config:
var db = new MyDbContext("NameOfConnectionStringInWebConfig");
You can pass a connection string Name, or Db Connection details (SqlConnection)
If you have a multi DB concept where the the DBs are added at runtime, the DB Connection approach is useful since the App.config doesnt have the connection Name.
You can of course add the connection names to app.config, or try the DB connection approach.
it gets fun to get that working when you get to the migration topic.
public class MyDbContext : DbContext
//ctor
public MyDbContext(string connectionName) : base(connectionName){ }
public MyDbContext(DbConnection dbConnection, bool contextOwnsConnection)
: base(dbConnection, contextOwnsConnection) { }

Entity Framework is trying to create a database, but its not what I want

I have a small asp.net mvc4 application (working fine in my local machine), that uses entity framework v4.1.0.0 with ADO.net DbContext Generator.(SQL Server 2008 r2)
I am adding newer versions of dlls required through the "Add Deployable Dependencies..." context menu in Visual Studio 2010.
I have a shared hosting with godaddy.com, I have uploaded the files to server and created the database, now here comes the problem.When I try to browse my site I get the following error:
CREATE DATABASE permission denied in database 'master'.
I looked this up around and found out that this error was caused by EF code first trying to create database.but i do not want EF code first to recreate the database, how do i turn off this automatic database creation altogether? I have no intentions of using the code-first feature whatsoever.
Please help.
put this code into the Application_Start() method of Global.asax or constructor on your DbContext class
Database.SetInitializer<MyContext>(null);
If you want to recreate database when POCO domains are changed, use following code instead of above
Database.SetInitializer<MyContext>(new DropCreateDatabaseIfModelChanges<MyContext>());
If you are using EF Migrations, this is what you set for it:
public sealed class DbConfiguration : DbMigrationsConfiguration<DatabaseContext>
{
public DbConfiguration()
{
AutomaticMigrationsEnabled = false;
}
}
But this doesn't answer the question on EF Code First itself. If the database already exists, then EF will not try to create it. So you just need to point it to an existing database. And to make sure the connection string name is the same as the name of the database context. If it is not, you need to provide it to it with some overrides:
public class DatabaseContext : DbContext
{
public DatabaseContext()
: base(ApplicationParameters.ConnectionStringName)
{
}
public DatabaseContext(string connectionStringName)
: base(connectionStringName)
{
}
}

Resources