How to use EntityFramework to generate Database Model in MVC
How to use EntityFramework to generate database model in MVC, aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
First open VS2013, create a new Web project mcc, and use the MVC template.
Right-click the reference, manage the NuGet package, and install EntityFramework.
Create a new class Employee under the Model file and add several properties, such as EmployeeId,FirstName,LastName,Salary.
Public int EmployeeId {get; set;} public string FirstName {get; set;} public string LastName {get; set;} public int Salary {get; set;}
Reference using System.ComponentModel.DataAnnotations; sets EmployeeId as the primary key.
Set the database connection string in Web.Config
Create a new folder DataAccessLayer under the root directory, create a new class SalesERPDAL, and inherit DbContext.
In CodeFirst schema, the corresponding database tables are generated based on entity classes.
Public class SalesERPDAL: DbContext {public SalesERPDAL (): base ("MyDBConnectString") / / Database connection string {this.Configuration.ProxyCreationEnabled = true; var aaa = new DbMigrationsConfiguration (); / / set the automatic migration attribute aaa.AutomaticMigrationsEnabled = true } protected override void OnModelCreating (DbModelBuilder modelBuilder) {modelBuilder.Entity () .ToTable ("TblEmployee"); / / set the name of the generated corresponding database table base.OnModelCreating (modelBuilder);} public DbSet Employees {get; set;}}
At this point, the basic setup is complete, and you begin to use the command to create the database and generate the table.
Open tools-NuGet package Manager-package Manager console
Enter the command: Enable-Migrations to allow migration.
Enter the command: Enable-Migrations-ContextTypeName aaa.DataAccessLayer.SalesERPDAL to specify the migration type.
Enter the command: Add-Migration to write the pending model changes to the code-based migration.
Name:update (random input)
Enter the command: Update-Database-Verbose, execute the build command, create the database, and update the table.
This is the answer to the question about how to use EntityFramework to generate the database model in MVC. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.