Search code examples
asp.net-mvc-5entity-framework-6asp.net-identity-2

Entity Framework 6 Code First Migrations using Identity user models in a separate project


Is it possible using EF6 Code First and MVC5 to put all the models, views, and controllers that involve ASP.Identity into its own class library project. So that over multiple web applications you could use that same DLL and already have all the views / controllers / models and be using the same security database for multiple applications?

We have several web applications with separate databases and one security database that handles all of them, and we weren't sure how to keep this model now that we're moving to EF6 Code First and MVC5.

If it is possible could someone point me to a tutorial of something similar or give me a basic outline of steps to go through?

Or if there is a better way to achieve my goal, of having one set of code to handle ASP.NET-Identity security that I can plug that dll into multiple web applications and get the same logic and databases?

Or is this not a good idea in general?

Very open to suggestion and advice. I appreciate it.


Solution

  • Yes it is. We do this with every project that we have. The structure is very simple. Just create a class library project to your solution, add EF to the project, then reference the class library from your main project.

    If using Code First Migrations be sure to select the class library project as the default project in the Package Manager console when running migrations or adding migrations.

    Here is a pseudo solution structure for your solution

    MySolution
      - MyWebApp
         reference: MyDAL
      -MyDAL
         reference: EF6
    

    The advantage that I find to this is that you can then reference the "DAL" class library from say a companion console application or windows form application, or a companion website, even in a different solution, and they will use the same code base.

    For example:

    MySolution
      - MyWebApp
         reference: MyDAL
      - MyDAL
         reference: EF6
      - MyOtherWebApp
         reference: MyDAL
    

    NOTE: Your data context will look for its connection string in the Web.config or App.config in the startup project. NOT the class library. This can be confusing at first... But once you think about how .NET compiles the application together into the final package, it makes sense.