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> { } }
The Model is the part of MVC which implements the domain logic. In simple terms, this logic is used to handle the data passed between the database and the user interface (UI). The Model is known as domain object or domain entity. The domain objects are stored under the Models folder in ASP.NET.
DbContext in dependency injection for ASP.NET CoreThe context is configured to use the SQL Server database provider and will read the connection string from ASP.NET Core configuration. It typically does not matter where in ConfigureServices the call to AddDbContext is made.
ViewModel = Model that is created to serve the view. ASP.NET MVC view can't have more than one model so if we need to display properties from more than one model in the view, it is not possible. ViewModel serves this purpose. View Model is a model class that can hold only those properties that are required for a view.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With