OnModelCreating fails when Context inherits from IdentityDbContext - ef-code-first

I had Data access implemented as below and was working
Contexct inheriting from DB Context
Had OnModelCreating for configurations
Manually addding configurations
However I modified my context to inherit from IdentityDbContext<ApplicationUser> and stopped manually generating configurations and after that the OnModelCreating fails and DB updates not happening at all.
If I remove the OnModelCreating, it works fine. As soon as I run the application.
Can any one guide me whats going wrong here?

I was missing the below line in the OnModelCreating method override. After that it started working.
base.OnModelCreating(modelBuilder);

Related

exception after upgrade ASP.NET Identity to 2.0

my project: VS2013, Entity Framework, Web forms, database first, Identity
I updated all NuGet packages of my project today (2014-4-15). Among them, Identity is upgraded to 2.0.0.0.
I thought things were going good, but unfortunately when I run the application, the following statement gives an exception.
namespace xxx.Models
{
// You can add User data for the user by adding more properties to your User class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("MyConnection")
{
}
}
...
}
The exception information is as follows. It asks me to do Code First Migration. But my project is a Database First webforms project. How can I solve this problem? Thanks!
An exception of type 'System.InvalidOperationException' occurred in Microsoft.AspNet.Identity.EntityFramework.dll but was not handled in user code
Additional information: The model backing the 'ApplicationDbContext' context has changed since the database was created.
This could have happened because the model used by ASP.NET Identity Framework has changed or the model being used in your application has changed.
To resolve this issue, you need to update your database. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=301867).
Before you update your database using Code First Migrations, please disable the schema consistency check for ASP.NET Identity by setting throwIfV1Schema = false in the constructor of your ApplicationDbContext in your application.
public ApplicationDbContext() : base("ApplicationServices", throwIfV1Schema:false)
You need to disable the schema consistency by doing what the error says. This is one time thing that happens when you upgrade from version 1.0 to 2.0.
public ApplicationDbContext() : base("MyConnection", throwIfV1Schema:false)
Next step - do the migrations.
Everything should work after that and you can remove this throwIfV1Schema:false
You can also take a look at this for more info
The problem is here :
public class ApplicationUser : IdentityUser
{
}
I think you should change to partial class to extend entity in Entity Framework. The reason is that EF will generate proxy class for each entity to connect to database.
The partial class should be write in the same namespace.

Can't initialize simple membershipprovider

I don't really know how to identify the problem I currently have.
I want to initialize the simple membership provider but I don't really know how to.
As seen here : How to Initialize SimpleMembershipProvider?
I try to add this above my accountController
[InitializeSimpleMembership]
The attribute is remaining underligned in red, and when I click on it, I can't "resolve" it.
If I try to add this in my App_Start :
WebSecurity.InitializeDatabaseConnection()
It is also underligned in red, and I can't resolve it.
When I add this in my "SignIn" action
Membership.ValidateUser(username, password)
I'm able to build my app. However, when I try to log in, I get an exception telling me that the SQL server was unreachable.
I've checked the version of System.Web.Mvc in my reference folder : it's version 4.0
The SimpleMembershipProvider is contained in the WebMatrix.WebData assembly. You will need to add a reference to this dll (WebMatrix.WebData.dll) to your project, and then either the appropriate using/Imports directives:
using WebMatrix.WebData; // C#
or
Imports WebMatrix.WebData ' VB.NET
Alternatively, you can fully qualify the class as WebMatrix.WebData.SimpleMembershipProvider every time you use something from the assembly, but I find it easier to use the using/Imports directives :)

How Orchard CMS does the logging?

I'm working with Orchard CMS and it is better CMS for me. I want to understand how it does the logging and whether I can add my own logging or not. I saw that Orchard uses NullLogger class and it does no work. I've opened the App_Data.Logs folder and have seen that there are the log files. But how? I searched in code where is the trick that replaces NullLogger with log4net (I guess this is log4net, because the log format and the formatting for log4net.config are very similar) but I haven't found this.
Can somebody answer me:
How Orchard does the logging?
Whether I can add my own logger and if yes what best practices exist to do this?
Thanks, Andrey.
An Autofac module (Orchard.Logging.LoggerModule to be precise) handles that. Basically - it scans each dependency and fills all properties of type ILogger with a reference to appropriate logger instance. Each dependency gets its own logger with name equal to full type name (including namespace) of a containing class.
The NullLogger is just a placeholder so accessing the property would not throw NullReferenceExceptions before the property is being set by Autofac.
Extending the default logging is a rather complicated task as it would involve doing three things:
create a custom implementation of ILoggerFactory (just like the default Orchard.Logging.CastleLoggerFactory) and
create an Autofac module that registers that implementation in the container (like the mentioned LoggerModule does)
suppress the current default logging module by decorating your new one with [OrchardSuppressDependency("Orchard.Logging.LoggingModule")]
UPDATE
Just realized I haven't addressed the most important part of the question here:)
Yes, Orchard uses log4net so you may alter the default settings via Config/log4net.config file.
There is a great article on how Orchard Logging works. (I am not sure if it is ok to copy and paste the entire article). This is the link: Injection Logger in Orchard
So the trick is this:
Whenever a class requires a Logger instance, all it needs to do is to
declare a ILogger property, that’s it. And later, in your class, you
can use this property to Logging at anytime
And how is this done?
When Orchard web application startup, the OrchardStarter will be used
to do most of the registration work.
In a few words, it looks all the code in all projects, gets all the classes that use an ILogger property, and implements it for you (if not implemented), using Castle's logger factory.

MVP Pattern : Separating the database dependency from the presenter?

Whenever I try to actually unit test a presenter and a mocked view, I end up running into too many database dependencies
public EditAccount(IAccountEditPage _view, ISession _session, IResponse _response)
{
}
public void view_SaveUser()
{
//Class that takes the view's data and persists it to DB
}
Obviously I can't write unit tests for this presenter because I have a concretion of using my model class that has a strong database dependency.
How am I supposed to removed the dependency on the database without constructor injecting every class that touches the database in my presenter? I don't want to do this every time in every view I have.
I'm using moq, if it helps.
Edit : Also I should mention that the code in "view_SaveUser" is very lean and isn't direct database access or anything like that. It's usually only a few lines. I'm not overstepping the scope of the presenter, AFAIK.
If you don't want to inject the instances on the constructor another option you have is using a setter injection using a IoC framework as Spring.Net or Castle Windsor to inject the dependencies.
Doing this, you would only need to specify on the framework configuration which classes are used for real code and for test project, dependencies would be automatically injected and you would avoid having to use the contructor.

EF 4.1 Code First and Existing Database and .NET Membership

I have a database called ApplicationName_Development running on SQL Server 2008 R2 Developer edition on my development box.
I added .NET membership tables to the database with no problem. When I tried to get Code First working I received the following error message:
The server encountered an error
processing the request. The exception
message is "Model compatibility cannot
be checked because the database does
not contain model metadata. Ensure
that IncludeMetadataConvention has
been added to the DbModelBuilder
conventions.
After some googling, I discovered that I had to delete the database and let EF create the database. That's fine but I lost all my .NET membership tables. I can go back in and add the membership tables again but if my model changes and EF needs to recreate the database then I have to add the membership tables in again.
How do I get around this?
This is how code-first work. Main idea of code first is that you do not touch your database because it is responsibility of the model to create the database. If you want to customize your database you must create custom IDatabaseInitializer and add your custom SQL.
public class MyDbInitializer : DropCreateDatabaseIfModelChanges<MyContext>
{
protected override void Seed(MyContext context)
{
// Here run your custom SQL commands
context.Database.ExecuteSqlCommand("CREATE TABLE ....");
}
}
Now you only need setup your cutom intializer on the startup of your application:
Database.SetInitializer<MyContext>(new MyDbInitializer());
If you don't want to do it this way you must manually maintain your database and set initializer to null.
Found a easier workaround here. I hope this helps.
http://www.paragm.com/ef-v4-1-code-first-and-asp-net-membership-service/
Another option could be to use the System.Web.Management namespace. I've had great success with the code below:
string connectionString = ConfigurationManager.ConnectionStrings["MyDatabaseContext"].ConnectionString;
string database = "MyDatabaseName";
SqlServices.Install(database, SqlFeatures.All, connectionString);
It will just create the database and after that you can add users with the standard membership API.
Here's another possibility.
If you look at the MvcMusicStore sample - there's a SampleData class that is responsible for seeding the database on a rebuild. The SampleData class inherits from DropCreateDatabaseIfModelChanges, and overrides the Seed method. This class is passed to the Database.SetInitializer in the Application_Start method in global.asax.
I was getting the same error as you until I changed the parent class of SampleData to CreateDatabaseIfNotExist.
Then you can override the Seed method to insert any data you desire at startup, without it blowing away the database.
While you are developing, create 2 databases and two connection strings. One for SqlMembership (using aspnet_regsql) and one for your EF Application. If you would like to merge them into a single DB in production, just change the connection string in web.config.release to be the same. Then, EF model changes will just drop your apps db and not your membership DB.
By treating your authentication component separately, you will naturally decouple your authentication system from your application system. Then, if you wish to change membership providers, you will be better setup.
As the system grows, you will likely need to support non-pure models without EF code first, so this is a good template for going down that path.
I found the easiest way without playing with anything else was the following.
I ran the application first time with DropAndRecreatedatabase always in the Initilizer.
This created my database for the first time.
Following this I changed this to DropCreateDatabaseIfModelChanges.

Resources