SimpleMembership initializer does not create all the tables - asp.net-mvc

Folks,
After creating a new ASP .NET MVC 4 application, here is what I did:
From the database explorer, deleted all the tables in the default connection.
Edited AccountModels.cs to and added a few more tables.
Updated UsersContext class to reference the new tables:
public class UsersContext : DbCOntext {
...
DbSet<Items> Items {get; set; }
}
Ran the application.
In the debugger, I see that the following line is invoked:
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
However, when I look at the database, only the five tables relevant to SimpleMembershipProvider are getting created. My additional tables are not getting created.
I am wondering if there is some step that I missed.
Thank you in advance for your help.
Regards,
Peter

You need to create another DbContext class for your domain model.
Using the same DbContext, UsersContext will cause you many problems in the future. I had so many problems with that. and turned out, you need a seperate DbContext for your domain model.

Thank you for your help. I eventually figured it out. The default InitializeSimpleMembershipAttribute class is geared to create only the required tables (and columns) for simple membership. You create your own initializer class that inherits from CreateDatabaseIfNotExists<>. Now, you can just delete and recreate an empty database. When you run your application, ALL your tables will automatically get created.
Peter

Related

Updating MVC Model From Database

I am still new to EF and MVC and how they work together so excuse my ignorance. I have a SQL DB that I generated the MVC Data Model from and I have recently added some fields to a couple tables and now I need to update those changes from my SQL DB into my Model1.edmx.
The issue is that when I went to update the Model from my DB, the update overwrote all of my [Display(Name = "DisplayName")] and [Required] for each field.
So, my question is this: Is there a way to maintain all of my current changes to the Model and just bring in the new fields without overwriting every table in the Model?
Edit: I have tried this: Add data annotations to a class generated by entity framework but to no success. Whenever I regenerate the Model from the database it just overwrites whatever classes I had there. I am creating a public class just like in the example but it gets wiped when I update the Model. Any ideas?
Any help would be awesome! Thanks!

MVC EF (Code First) - Creating relationship with AspNetUsers and Custom Tables

new to MVC and EF. Trying to achieve the following:
A new site with individual user accounts
Create a DB table "Leagues" whereby when creating a new league the LeagueAdmin is an ApplicationUser
I followed this tutorial to try to achieve what i wanted. When i start the application I am able to register new users without issue. However, when I go to create a new league I get the following error:
"Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations."
I have tried many fixes i've read about but they tend to lead me down a path of increasingly complex errors. I feel like this should be simple enough that i'd like to understand this error first before tackling the next.
VS Project Source is here
Most probably, your database does not contain a _MigrationHistory table.
Add this code to your DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
}
Go to Package Manager Console by following View -> Other Windows -> Package Manager Console
And write following commands:
enable-migrations
add-migration InitialCreate
update-database
Alternatively;
You can add this code to your DbContext;
static LeagueContext()
{
Database.SetInitializer<LeagueContext>(
new DropCreateDatabaseAlways<LeagueContext>());
}

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.

Error:'Unsupported context type' while creating a new controller

I am going to implement MvcMusicStore using ASP.NET MVC3, Linq to Sql class instead of Entity Framework, MS SQL Server 2008 pro instead of express ed.
I got the tutorial from mvcmusicstore.codeplex.com
I used Linq to Sql class and the Datacontext is MvcMusicSrotedataContext. When i try to create a new class using this
it shows an error in a new window when i click add button Error:'Unsupported context Type'
So, could you please help me to solve this?
Thank You.
The built-in MVC scaffolding doesn't support Linq to SQL -- you'll have to use Entity Framework instead. (Or don't use the scaffolding, build your own controller/action logic manually. Or use a scaffolding plugin that supports Linq to SQL.)
I got the same issue with EF. I am using the VS 2012.
Background:
The reason for my case was.. this auto generation process (Scaffolding) seems not recognize the partial class concept.
I used the model first approach and I have used inheritance with the entities.
Ex: entity “B” and “C” is inherited from “A”
So in my generated model class “DataModelContainer” which is inherited from “DbContext”,
There is no definition for “DbSet” and “DbSet”
i.e: the following two lines were not there
public DbSet<B> B { get; set; }
public DbSet<C> C { get; set; }
Generated “DataModelContainer” class I a partial class, so I completed the other part, using the concept of partial class. And this would be a problem for Scaffolding.
Solution
My workaround was, just removed the partial class I added manually. And added the definitions for “DbSet” and “DbSet” in to the auto generated class.
The problem with this solution is, I have to repeat the same thing when I regenerate the model classes.

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?

Resources