”;
The component ‘Model’ is responsible for managing the data of the application. It responds to the request from the view and it also responds to instructions from the controller to update itself.
Model classes can either be created manually or generated from database entities. We are going to see a lot of examples for manually creating Models in the coming chapters. Thus in this chapter, we will try the other option, i.e. generating from the database so that you have hands-on experience on both the methods.
Create Database Entities
Connect to SQL Server and create a new database.
Now run the following queries to create new tables.
CREATE TABLE [dbo].[Student]( [StudentID] INT IDENTITY (1,1) NOT NULL, [LastName] NVARCHAR (50) NULL, [FirstName] NVARCHAR (50) NULL, [EnrollmentDate] DATETIME NULL, PRIMARY KEY CLUSTERED ([StudentID] ASC) ) CREATE TABLE [dbo].[Course]( [CourseID] INT IDENTITY (1,1) NOT NULL, [Title] NVARCHAR (50) NULL, [Credits] INT NULL, PRIMARY KEY CLUSTERED ([CourseID] ASC) ) CREATE TABLE [dbo].[Enrollment]( [EnrollmentID] INT IDENTITY (1,1) NOT NULL, [Grade] DECIMAL(3,2) NULL, [CourseID] INT NOT NULL, [StudentID] INT NOT NULL, PRIMARY KEY CLUSTERED ([EnrollmentID] ASC), CONSTRAINT [FK_dbo.Enrollment_dbo.Course_CourseID] FOREIGN KEY ([CourseID]) REFERENCES [dbo].[Course]([CourseID]) ON DELETE CASCADE, CONSTRAINT [FK_dbo.Enrollment_dbo.Student_StudentID] FOREIGN KEY ([StudentID]) REFERENCES [dbo].[Student]([StudentID]) ON DELETE CASCADE )
Generate Models Using Database Entities
After creating the database and setting up the tables, you can go ahead and create a new MVC Empty Application. Right-click on the Models folder in your project and select Add → New Item. Then, select ADO.NET Entity Data Model.
In the next wizard, choose Generate From Database and click Next. Set the Connection to your SQL database.
Select your database and click Test Connection. A screen similar to the following will follow. Click Next.
Select Tables, Views, and Stored Procedures and Functions. Click Finish. You will see the Model View created as shown in the following screenshot.
The above operations would automatically create a Model file for all the database entities. For example, the Student table that we created will result in a Model file Student.cs with the following code −
namespace MvcModelExample.Models { using System; using System.Collections.Generic; public partial class Student { public Student() { this.Enrollments = new HashSet(); } public int StudentID { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public Nullable EnrollmentDate { get; set; } public virtual ICollection Enrollments { get; set; } } }
”;