通过 MVC 5 使用 Entity Framework 6 Code First (2)

https://docs.microsoft.com/zh-cn/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/

 SQL Server (Full Editions) Connection String Examples

  
    
  

 

PM> Install-Package EntityFramework
PM> update-database

 通过 MVC 5 使用 Entity Framework 6 Code First (2)_第1张图片

通过 MVC 5 使用 Entity Framework 6 Code First (2)_第2张图片

 通过 MVC 5 使用 Entity Framework 6 Code First (2)_第3张图片

 通过 MVC 5 使用 Entity Framework 6 Code First (2)_第4张图片

 通过 MVC 5 使用 Entity Framework 6 Code First (2)_第5张图片

 

安装 Entity Framework 6

  1. 工具菜单中,选择NuGet 包管理器,然后选择程序包管理器控制台

  2. 在中程序包管理器控制台窗口中,输入以下命令:

    PM> Install-Package EntityFramework
    
    
    正在尝试收集与目标为“.NETFramework,Version=v4.7.2”的项目“ContosoUniversity”有关的包“EntityFramework.6.2.0”的依赖项信息
    收集依赖项信息花费时间 46.61 ms
    正在尝试解析程序包“EntityFramework.6.2.0”的依赖项,DependencyBehavior 为“Lowest”
    解析依赖项信息花费时间 0 ms
    正在解析操作以安装程序包“EntityFramework.6.2.0”
    已解析操作以安装程序包“EntityFramework.6.2.0”
    从“nuget.org”检索包“EntityFramework 6.2.0” 
    正在将程序包“EntityFramework.6.2.0”添加到文件夹“D:\csharp-demo\ContosoUniversity\packages”
    已将程序包“EntityFramework.6.2.0”添加到文件夹“D:\csharp-demo\ContosoUniversity\packages”
    已将程序包“EntityFramework.6.2.0”添加到“packages.config”
    正在执行脚本文件“D:\csharp-demo\ContosoUniversity\packages\EntityFramework.6.2.0\tools\init.ps1”
    正在执行脚本文件“D:\csharp-demo\ContosoUniversity\packages\EntityFramework.6.2.0\tools\install.ps1”
    
    Type 'get-help EntityFramework' to see all available Entity Framework commands.
    已将“EntityFramework 6.2.0”成功安装到 ContosoUniversity
    执行 nuget 操作花费时间 3.63 sec
    已用时间: 00:00:05.1479976
    PM> 

    views/shared\_Layout.cshtml

 





    
    
    @ViewBag.Title - Contoso University
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")


    
    
@RenderBody()

© @DateTime.Now.Year - Contoso University

@Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false)

Views\Home\Index.cshtml

 

@{
    ViewBag.Title = "Home Page";
}

Contoso University

ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.

Learn more »

Welcome to Contoso University

Contoso University is a sample application that demonstrates how to use Entity Framework 6 in an ASP.NET MVC 5 web application.

Learn more »

Get more libraries

NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.

Learn more »

Web Hosting

You can easily find a web hosting company that offers the right mix of features and price for your applications.

Learn more »

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
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 Students { get; set; }
        public DbSet Enrollments { get; set; }
        public DbSet Courses { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove();
        }
    }
}
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
    {
        protected override void Seed(SchoolContext context)
        {
            var students = new List
            {
            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
            {
            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
            {
            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();
        }
    }
}

Web.config




  
    
    

创建一个学生控制器和视图

现在将创建一个用于显示数据 web 页。 自动请求数据的过程将触发创建数据库。 您将首先创建一个新的控制器。 但这样做之前,请生成项目以使模型和上下文类可用于 MVC 控制器基架。

  1. 右键单击控制器中的文件夹解决方案资源管理器,选择添加,然后单击新基架项

  2. 在中添加基架对话框中,选择包含的 MVC 5 控制器视图,使用实体框架,然后选择添加

通过 MVC 5 使用 Entity Framework 6 Code First (2)_第6张图片

 

在中添加控制器对话框中,进行以下选择,然后选择添加:

  • 模型类:Student (ContosoUniversity.Models)。 (如果看不到下拉列表中的此选项,生成项目,然后重试。)

  • 数据上下文类: SchoolContext (ContosoUniversity.DAL)

  • 控制器名称: StudentController (不 StudentsController)。

  • 保留其他字段的默认值。

 通过 MVC 5 使用 Entity Framework 6 Code First (2)_第7张图片

 看看生成的数据库关系图,我们可以使用数据库表及其关系图自动生成代码

通过 MVC 5 使用 Entity Framework 6 Code First (2)_第8张图片

USE [SchoolContext]
GO
/****** Object:  Table [dbo].[__MigrationHistory]    Script Date: 2018/11/22 13:40:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[__MigrationHistory](
	[MigrationId] [nvarchar](150) NOT NULL,
	[ContextKey] [nvarchar](300) NOT NULL,
	[Model] [varbinary](max) NOT NULL,
	[ProductVersion] [nvarchar](32) NOT NULL,
 CONSTRAINT [PK_dbo.__MigrationHistory] PRIMARY KEY CLUSTERED 
(
	[MigrationId] ASC,
	[ContextKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Course]    Script Date: 2018/11/22 13:40:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Course](
	[CourseID] [int] NOT NULL,
	[Title] [nvarchar](max) NULL,
	[Credits] [int] NOT NULL,
 CONSTRAINT [PK_dbo.Course] PRIMARY KEY CLUSTERED 
(
	[CourseID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Enrollment]    Script Date: 2018/11/22 13:40:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Enrollment](
	[EnrollmentID] [int] IDENTITY(1,1) NOT NULL,
	[CourseID] [int] NOT NULL,
	[StudentID] [int] NOT NULL,
	[Grade] [int] NULL,
 CONSTRAINT [PK_dbo.Enrollment] PRIMARY KEY CLUSTERED 
(
	[EnrollmentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Student]    Script Date: 2018/11/22 13:40:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Student](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[LastName] [nvarchar](max) NULL,
	[FirstMidName] [nvarchar](max) NULL,
	[EnrollmentDate] [datetime] NOT NULL,
 CONSTRAINT [PK_dbo.Student] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
ALTER TABLE [dbo].[Enrollment]  WITH CHECK ADD  CONSTRAINT [FK_dbo.Enrollment_dbo.Course_CourseID] FOREIGN KEY([CourseID])
REFERENCES [dbo].[Course] ([CourseID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Enrollment] CHECK CONSTRAINT [FK_dbo.Enrollment_dbo.Course_CourseID]
GO
ALTER TABLE [dbo].[Enrollment]  WITH CHECK ADD  CONSTRAINT [FK_dbo.Enrollment_dbo.Student_StudentID] FOREIGN KEY([StudentID])
REFERENCES [dbo].[Student] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Enrollment] CHECK CONSTRAINT [FK_dbo.Enrollment_dbo.Student_StudentID]
GO

 

你可能感兴趣的:(C#,ASP.NET,MVC,5,ASP.NET,MVC,5)