Entity Framework 5 multiple databases - asp.net-mvc

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) { }

Related

MVC project not creating database

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

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.

Asp mvc 3 noobie: Why is the code-first method not building my DB on sql server?

I am an ASP MVC 3 noobie who has done a few tutorials. Now I'm trying to build a site. All of the tutorials on the microsoft website emphasize the code-first approach: you define your model with code and then create a datacontext and then the entity framework creates/manages the DB based on your code.
I set up an Employees class and a DataBaseContext class that inherits from DbContext. I added a connection string to Web.config connection string that successfully links DataBaseContext to an already existing empty DB on SQL server. EDIT= That was the problem. See my answer below
But when I try to run the Employees controller created thru scaffolding, I get this error
Invalid object name 'dbo.Employees'.
Description: An unhandled exception occurred during the execution of...
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.Employees'.
I followed this post SqlException (0x80131904): Invalid object name 'dbo.Categories' and realized that if I create an employees table on the DB, this excpetion goes away (I get a new one saying that the column names are invalid).
But I thought the whole point of MVC 3 is that the framework will make the DB for you based on the code.
Maybe I need a line of code in the Global.asax Application_start() to create the database? Here is my application_start method:
Sub Application_Start()
AreaRegistration.RegisterAllAreas()
RegisterGlobalFilters(GlobalFilters.Filters)
RegisterRoutes(RouteTable.Routes)
End Sub
Here is the code for Employee:
Public Class Employee
Property EmployeeID As Integer
Property First As String
Property Last As String
Property StartDate As DateTime
Property VacationHours As Integer
Property DateOfBirth As DateTime 'in case two employees have the same name
End Class
Here is the code for the DB context:
Imports System.Data.Entity
Public Class DatabaseContext
Inherits DbContext
Public Property Employee As DbSet(Of Employee)
Public Property AnnualLeave As DbSet(Of AnnualLeave)
End Class
What am I missing?
By default EF uses DropCreateDatabaseIfModelChanges<TContext> database initializer. Accordingly to the MSDN:
An implementation of IDatabaseInitializer<TContext> that will delete, recreate, and optionally re-seed the database with data only if the model has changed since the database was created. This is achieved by writing a hash of the store model to the database when it is created and then comparing that hash with one generated from the current model.
Since the database was created manually, EF can't find the hash and decides do not perform any further initialization logic.
You might want to look into this article, same question successfully answered already.
Or it can be this (also resolved successfully)
Answer to your problem is most likely one of the two.
Hope this will help you
Does the name you're specifying for your connection string match the name of your database context?
For example:
Context
var myDbContext = new MyDbContext();
Connection string
<connectionStrings>
<add name="MyDbContext" connectionString="YOUR.CONNECTION.STRING" providerName="System.Data.SqlServer" />
</connectionStrings>
Try and see if this post I wrote about DbContext with MVC works for you: Code-First
Not a lot to be done to get this to work, but there are a few things that are easily missed that will cause a bunch of head aches.
hope this helps
I had already created a database with that name on SQL server. Once I deleted the existing database, the code first framework created the tables for me like it was supposed to. It seems like if the database already exists, the framework won't set up the tables for you. It wants to create the whole DB from scratch.
You were using AdventureWorks Database?
It has it's own schema assigned to the employees table. HumanResources.Employees and not the default dbo.Employees.
Even though I've identified the problem, I don't know the solution to using the database as configured with the HumanResources schema.
Anybody know?

Multiple Web.config In Asp.net Mvc3 Application

My project specifications are ASP.net MVC3 Application with Entity Framework.
The problem is that Customer wise the database will be created. Individual application individual database is working fine for me.
But i want a single application and multiple databases should be used with that.
How to achieve the same?
Instead of creating your entity connections using the default constructor and web.config-driven connection string, you need to manually build the entity connection string and feed it into it on construction using one of the other constructors. There's usually one that takes a string, and another that takes an EntityConnection instance as well.
If the only thing that changes is the name of the database, then you can probably get away with a format string - where you perhaps take the one that's currently in your web.config - which will look something like this:
metadata=res://*;provider=System.Data.SqlClient;provider connection string="Data Source=[server];Initial Catalog=[db];User ID=[user];Password=[password]"
Note - [server], [db], [user] and [password] here are placeholders.
And simply replace the [db] with {0}.
Then - assuming you can derive a database name from a user you might do something like this following:
public string BaseConnectionString {
get{
//TODO: Get base connection string - can just bake in the constant string with
//with the format placeholder. A better thing would be to add it as an
//AppSetting in web.config
}
}
//this now becomes you're primary way of getting a database connection for a user.
public MyEntities GetEntities(User user)
{
var eConnectionString = GetConnectionString(user);
return new MyEntities(eConnectionString);
}
public string GetConnectionString(User user)
{
var dbName = get_db_name_for_user(user);
return string.Format(BaseConnectionString, dbName);
}
This is but one way to achieve this. In an IOC environment it would be possible to hide all of this behind a simple Resolve<> call.

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