Models.ApplicationDbContext for all models in an Asp.Net MVC 5 application?

51,809

Solution 1

There is an excellent video explaining that matter. Just check the free ASP.NET MVC 5 Fundamentals course by Scott Allen. The exact answer is here (starts at 3:30).

Solution 2

I would advise keeping them separate. There is really no reason to couple two parts of the system together. To add another DbContext just add a file to models called YourContext.cs.

public class YourContext: DbContext
{
    public YourContext() : base("name=YourContext")
    {
    }

    // Add a DbSet for each one of your Entities
    public DbSet<Room> Rooms { get; set; }
    public DbSet<Meal> Meals { get; set; }
}

Then in the root web.config

<add name="YourContext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=YourContext; Integrated Security=True"" providerName="System.Data.SqlClient" />

When you run enable-migrations in the package manager console you will be asked which dbcontext you want to migrate. Pick YourContext.

EDIT: No need to add repos / unit of work the Entity Framework does this for you.

Solution 3

Please note: This was written as in beta2 where ALLOT has changed! Hopefully most of it will stick but there are no guarantees until RC.

DO NOT USE NuGET package manger (until RC) as it does NOT pick-up on the .NET 5 packages required and it will install EF 6 and mess up your project. (We are after EF 7)

In the projects.json you need to have the following dependencies. (or beta2 when its out, or the latest on RC)

    "EntityFramework": "7.0.0-beta1",
    "EntityFramework.Relational": "7.0.0-beta1",
    "EntityFramework.Commands": "7.0.0-beta1",
    "EntityFramework.Migrations": "7.0.0-beta1",
    "EntityFramework.SqlServer": "7.0.0-beta1"

Add a new folder DBContexts and add a c sharp file with your new context stuff.

  public class BlaBlaDB : DbContext
    {
        public DbSet<Models.MyOtherModel> MyOtherModels { get; set; }

        protected override void OnConfiguring(DbContextOptions options)
        {
            options.UseSqlServer();
        }
    }

and in your config.json make sure to add a connection string, the exact same as the IdentityDB just with you new name. Then in startup.json register your databse.

 services.AddEntityFramework(Configuration)
                .AddSqlServer()
                .AddDbContext<DataContexts.IdentityDB>()
                .AddDbContext<DataContexts.BlaBlaDB>();

This has to compile because k will run this project and use the startup to inject your context and then execute everything you need. As of now VS2015 Beta does NOT have all/ or they do not work, the command for EF.

You need to go and install KRE for Windows.

Open command prompt, browse to your project directory, enter the solution and enter the following commands.

k ef context list
k ef migration add -c (context.from.above) initial
k ef migration apply -c (context.from.above)

You now have multi context migration. Just keep on adding context and repeat this as you need it. I used this on localdb, as the default project set-up so that it can work stand alone in any environment, like Linux.

Please Note: You still need to create a Service, containing the Interface and Implementation and then register that in startup.json More information here

Share:
51,809
ca9163d9
Author by

ca9163d9

Updated on June 07, 2020

Comments

  • ca9163d9
    ca9163d9 almost 4 years

    I've creating an Asp.Net MVC 5 website. I will need to add customized fields in ApplicationUser and associate (add foreign keys) it with other models. I think I should just use one context type. However, the code scaffold already generate the following ApplicationDbContext class. Can I just put all my public DbSet<...> ... { get; set; } in the class? Or is there a better pattern?

    namespace MyApp.Models
    {
        // You can add profile 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 : User
        {  
        }
    
        public class ApplicationDbContext : IdentityDbContextWithCustomUser<ApplicationUser>
        {
        }
    }
    
  • Antevirus
    Antevirus over 10 years
    So basically what you're saying is to have two separate databases?
  • stink
    stink over 10 years
    Yes. EF will merge the databases when the site is published to a server... EF does so much for you it's almost to the point where during development you don't have think about the database architecture of the application.
  • stink
    stink over 10 years
    To access user stuff from anywhere in the application. User.Identity.Name.[Method] User.Identity.GetUserId(); User.Identity.GetUserName();
  • Geethanga
    Geethanga almost 10 years
    @stink I have used this approach, but it gives me a headache when deploying the application. If you had just one context with migrations enabled it will automatically apply pending migrations. But with two or more contexts it doesn't really work, you have to manually run Update-Database on each changed context. Or am I doing anything wrong?
  • stink
    stink almost 10 years
    @Geethanga check out the post by below. I would trust Scott Allen's solution before mine.
  • Piotr Kula
    Piotr Kula over 9 years
    Yea man, that tutorial link definitely explained it properly. You just need to reuse the connection strings in the new contexts, which is now stored in the config.json instead of the BaseClass constructor.
  • Piotr Kula
    Piotr Kula over 9 years
    PLease note: DO NOT USE PACKAGE MANAGER WITH BETA, Use the command line KVM and K
  • ca9163d9
    ca9163d9 over 9 years
    Is it possible to create foreign key constraint on a table in DataContexts.BlaBlaDB to reference a table in DataContexts.IdentityDB?
  • Piotr Kula
    Piotr Kula over 9 years
    Ahhhhh..... That might not be possible. I am fresh on this too but I hope there is a way. Separate context might cause an issue but lets see. Have you managed to do that in EF6? There is also the Service Part (injection of Interface) missing here. I need to add that, everything is DI now.. erh... dont really fancy that but I suppose its the way forward.
  • Stephen Hosking
    Stephen Hosking about 9 years
    I highly recommend this video. It's only 10 min.
  • kodkod
    kodkod over 8 years
    Care to summarize the answer here, in case the video link breaks some day?
  • Chris Hawkes
    Chris Hawkes over 8 years
    Why is there not a clear way of doing this with ASP.NET? Although the video is helpful it leaves a lot of questions hanging as to whether or not this is a clean implementation one would want to use in a production website.
  • JSideris
    JSideris about 8 years
    Hmm this, per se, is a bit murky on the topic of how to create references to the AspNetUsers table from your own classes. Expanding ApplicationDbContext is a bit of a forbidden fruit I guess.
  • midoriha_senpai
    midoriha_senpai about 7 years
    Video still exists on Pluralsight: ASP.NET MVC 5 Fundamentals by Scott Allen; Module: 6 ("Entity Framework 6"), Clip: 2 ("Starting Up"). Course URL: link, and exact clip URL: link.