创建ASP.NET MVC项目

标签: C#  ASP.NET MVC

以创建一个简单的大学网站为例
借鉴网站

在这里插入图片描述

  1. 打开Visual Studio并使用ASP.NET Web Application (.NET Framework)模板创建一个C#Web项目。将项目命名为ContosoUniversity,然后选择OK
    在这里插入图片描述
    2. 在 New ASP.NET Web Application - ContosoUniversity中,选择 MVC,然后点击OK

在这里插入图片描述

3. 设置网站样式(随便做不做)

  • 打开Views \ Shared \ _Layout.cshtml,然后进行以下更改:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Contoso University</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="navbar-inner">
            <div class="container">
                <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Contoso University", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                <div class="nav-collapse collapse">
                    <ul class="nav">
                        <li>@Html.ActionLink("Home", "Index", "Home")</li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Students", "Index", "Student")</li>
                        <li>@Html.ActionLink("Courses", "Index", "Course")</li>
                        <li>@Html.ActionLink("Instructors", "Index", "Instructor")</li>
                        <li>@Html.ActionLink("Departments", "Index", "Department")</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - Contoso University</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>
  • 在Views \ Home \ Index.cshtml中,用以下代码替换文件的内容,以用与此应用程序有关的文本替换有关ASP.NET和MVC的文本:
@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>Contoso University</h1>
</div>
<div class="row">
    <div class="col-md-4">
        <h2>Welcome to Contoso University</h2>
        <p>Contoso University is a sample application that
        demonstrates how to use Entity Framework 6 in an 
        ASP.NET MVC 5 web application.</p>
    </div>
    <div class="col-md-4">
        <h2>Build it from scratch</h2>
        <p>You can build the application by following the steps in the tutorial series on the ASP.NET site.</p>
        <p><a class="btn btn-default" href="http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/">See the tutorial &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Download it</h2>
        <p>You can download the completed project.</p>
        <p><a class="btn btn-default" href="https://webpifeed.blob.core.windows.net/webpifeed/Partners/ASP.NET%20MVC%20Application%20Using%20Entity%20Framework%20Code%20First.zip">Download &raquo;</a></p>
    </div>
</div>
  • 安装EF6
    1)、从“ 工具”菜单中,选择“ NuGet软件包管理器”,然后选择“ 软件包管理器控制台”。
    2)、在“ 程序包管理器控制台”窗口中,输入以下命令:
Install-Package EntityFramework
  • 创建数据模型:
    学生实体:
    在Models文件夹中,右键单击解决方案资源管理器中的文件夹并选择Add > Class,创建一个名为Student.cs的类文件。将模板代码替换为以下代码:
using System;
using System.Collections.Generic;

namespace ContosoUniversity.Models
{
    public class Student
    {
        public int ID { get; set; }
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
        public DateTime EnrollmentDate { get; set; }
        
        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
}
  • 注册实体:
    在“ model”文件夹中,创建Enrollment.cs并将现有代码替换为以下代码:
namespace ContosoUniversity.Models
{
    public enum Grade
    {
        A, B, C, D, F
    }

    public class Enrollment
    {
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }
        public Grade? Grade { get; set; }
        
        public virtual Course Course { get; set; }
        public virtual Student Student { get; set; }
    }
}
  • 课程实体:
    在“ model”文件夹中,创建Course.cs,将模板代码替换为以下代码:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

namespace ContosoUniversity.Models
{
    public class Course
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }
        
        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
}
  • 创建数据库上下文:
    在ContosoUniversity项目的文件夹,右键单击该项目解决方案资源管理器,然后单击添加,然后单击新建文件夹。将新文件夹命名为DAL(用于数据访问层)。在该文件夹中,创建一个名为SchoolContext.cs的新类文件,并将模板代码替换为以下代码:
using ContosoUniversity.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace ContosoUniversity.DAL
{
    public class SchoolContext : DbContext
    {
    
        public SchoolContext() : base("SchoolContext")
        {
        }
        
        public DbSet<Student> Students { get; set; }
        public DbSet<Enrollment> Enrollments { get; set; }
        public DbSet<Course> Courses { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}
  • 用测试数据初始化数据库:
    当应用程序运行时,Entity Framework可以自动为您创建(或删除并重新创建)数据库。您可以指定每次应用程序运行时或仅在模型与现有数据库不同步时才应执行此操作。您还可以编写一种Seed方法,在创建数据库后,Entity Framework会自动调用该方法,以使用测试数据填充该数据库。
    默认行为是仅在数据库不存在时创建数据库(如果模型已更改且数据库已经存在,则引发异常)。在本节中,您将指定每当模型更改时都应删除并重新创建数据库。删除数据库会导致所有数据丢失。通常在开发过程中是可以的,因为该Seed方法将在重新创建数据库时运行并重新创建测试数据。但是在生产环境中,您通常不想每次需要更改数据库架构时都丢失所有数据。稍后,您将看到如何通过使用“代码优先迁移”来更改数据库架构而不是删除并重新创建数据库来处理模型更改。

在DAL文件夹中,创建一个名为SchoolInitializer.cs的新类文件,并将模板代码替换为以下代码,这将导致在需要时创建数据库并将测试数据加载到新数据库中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using ContosoUniversity.Models;

namespace ContosoUniversity.DAL
{
    public class SchoolInitializer : System.Data.Entity. DropCreateDatabaseIfModelChanges<SchoolContext>
    {
        protected override void Seed(SchoolContext context)
        {
            var students = new List<Student>
            {
            new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")},
            new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01")},
            new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2003-09-01")},
            new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2002-09-01")},
            new Student{FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse("2002-09-01")},
            new Student{FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse("2001-09-01")},
            new Student{FirstMidName="Laura",LastName="Norman",EnrollmentDate=DateTime.Parse("2003-09-01")},
            new Student{FirstMidName="Nino",LastName="Olivetto",EnrollmentDate=DateTime.Parse("2005-09-01")}
            };

            students.ForEach(s => context.Students.Add(s));
            context.SaveChanges();
            var courses = new List<Course>
            {
            new Course{CourseID=1050,Title="Chemistry",Credits=3,},
            new Course{CourseID=4022,Title="Microeconomics",Credits=3,},
            new Course{CourseID=4041,Title="Macroeconomics",Credits=3,},
            new Course{CourseID=1045,Title="Calculus",Credits=4,},
            new Course{CourseID=3141,Title="Trigonometry",Credits=4,},
            new Course{CourseID=2021,Title="Composition",Credits=3,},
            new Course{CourseID=2042,Title="Literature",Credits=4,}
            };
            courses.ForEach(s => context.Courses.Add(s));
            context.SaveChanges();
            var enrollments = new List<Enrollment>
            {
            new Enrollment{StudentID=1,CourseID=1050,Grade=Grade.A},
            new Enrollment{StudentID=1,CourseID=4022,Grade=Grade.C},
            new Enrollment{StudentID=1,CourseID=4041,Grade=Grade.B},
            new Enrollment{StudentID=2,CourseID=1045,Grade=Grade.B},
            new Enrollment{StudentID=2,CourseID=3141,Grade=Grade.F},
            new Enrollment{StudentID=2,CourseID=2021,Grade=Grade.F},
            new Enrollment{StudentID=3,CourseID=1050},
            new Enrollment{StudentID=4,CourseID=1050,},
            new Enrollment{StudentID=4,CourseID=4022,Grade=Grade.F},
            new Enrollment{StudentID=5,CourseID=4041,Grade=Grade.C},
            new Enrollment{StudentID=6,CourseID=1045},
            new Enrollment{StudentID=7,CourseID=3141,Grade=Grade.A},
            };
            enrollments.ForEach(s => context.Enrollments.Add(s));
            context.SaveChanges();
        }
    }
}

告诉EF使用初始化程序类,在Web.config中的中添加如下代码:

<contexts>
    <context type="ContosoUniversity.DAL.SchoolContext, ContosoUniversity">
      <databaseInitializer type="ContosoUniversity.DAL.SchoolInitializer, ContosoUniversity" />
    </context>
  </contexts>
  • 设置EF 6以使用LocalDB:
    appSettings元素之前添加如下代码:
<connectionStrings>
    <add name="SchoolContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=ContosoUniversity1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
  • !!!!构建项目:Ctrl+Shift+B 必须有
  • 创建控制器和视图:
    1)、用鼠标右击Controllers文件夹,选择Add,然后单击New Scaffolded Item
    2)、在“ Add Scaffold”对话框中,选择MVC 5 Controller with views, using Entity Framework,然后选择“ Add
    在这里插入图片描述In the Add Controller dialog box, make the following selections, and then choose Add:
    1)、Model class: Student (ContosoUniversity.Models). (If you don’t see this 2)、option in the drop-down list, build the project and try again.)
    3)、Data context class: SchoolContext (ContosoUniversity.DAL).
    4)、Controller name: StudentController (not StudentsController).
    Leave the default values for the other fields.
  • 运行
版权声明:本文为qq_36924683原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_36924683/article/details/102902411