天天看點

MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

原文:http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

By  Tom Dykstra |July 30, 2013 Translated by litdwg

Contoso University示例網站示範如何使用Entity Framework 5建立ASP.NET MVC 4應用程式。

Entity Framework有三種處理資料的方式: Database First, Model First, and Code First. 本指南使用代碼優先。其它方式請查詢資料。

示例程式是為Contoso University建立一個網站。功能包括:學生管理、課程建立、教師配置設定。 本系列指南逐漸講述如何實作這一網站程式。

本示例程式基于 ASP.NET MVC.如果使用 ASP.NET Web Forms model, 請檢視 Model Binding and Web Forms系列指南和 ASP.NET Data Access Content Map.

如有問題,可在這些讨論區提問: ASP.NET Entity Framework forum, the Entity Framework and LINQ to Entities forum, or StackOverflow.com.

(此指南的舊版本請檢視 the EF 4.1 / MVC 3 e-book.) 

Contoso University 應用程式

本指南将建立一個簡單的大學網站.

使用者可檢視或更新學生、課程、教師的資訊,以下是相關截圖:

MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)
MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

UI風格延續了預設模闆的風格,以便更多關注于如何使用Entity Framework。

需求

使用 Visual Studio 2012 or Visual Studio 2012 Express for Web, 可從以下連結擷取相關需求軟體:

Windows Azure SDK for Visual Studio 2012

如果已經安裝 Visual Studio,此連結将隻安裝缺少的元件.如果沒有Visual Studio, 将安裝Visual Studio 2012 Express for Web. 你也可使用Visual Studio 2013,但一些步驟和截圖有所不同.

若使用 Visual Studio 2010,需要安裝MVC 4 和 SQL Server LocalDB.

建立MVC Web程式

建立程式如下:

MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

選擇 Internet Application template.

選擇 Razor

點選OK.

MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

設定網站風格

菜單、布局有少許變動.

打開Views\Shared\_Layout.cshtml, 修改如下:黃色為修改後内容.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title - Contoso University</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <header>
            <div class="content-wrapper">
                <div class="float-left">
                    <p class="site-title">@Html.ActionLink("Contoso University", "Index", "Home")</p>
                </div>
                <div class="float-right">
                    <section id="login">
                        @Html.Partial("_LoginPartial")
                    </section>
                    <nav>
                        <ul id="menu">
                            <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>
                    </nav>
                </div>
            </div>
        </header>
        <div id="body">
            @RenderSection("featured", required: false)
            <section class="content-wrapper main-content clear-fix">
                @RenderBody()
            </section>
        </div>
        <footer>
            <div class="content-wrapper">
                <div class="float-left">
                    <p>&copy; @DateTime.Now.Year - Contoso University</p>
                </div>
            </div>
        </footer>

        @Scripts.Render("~/bundles/jquery")
        @RenderSection("scripts", required: false)
    </body>
</html>      

上面做了兩點改變:

  • 把 "My ASP.NET MVC Application" 和"your logo here" 替換為"Contoso University".
  • 添加一些後面用到的超連結

在Views\Home\Index.cshtml, 替換為如下代碼:

@{
    ViewBag.Title = "Home Page";
}
@section featured {
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1>@ViewBag.Title.</h1>
                <h2>@ViewBag.Message</h2>
            </hgroup>
        </div>
    </section>
}      

在 Controllers\HomeController.cs, 把 

ViewBag.Message

 值替換為 "Welcome to Contoso University!":

public ActionResult Index()
{
    ViewBag.Message = "Welcome to Contoso University";

    return View();
}      

 CTRL+F5 運作,界面如下.

MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

建立資料模型

先建立如下三個資料模型:

MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

Student

 and 

Enrollment

 實體是一對多關系,, 

Course

 and 

Enrollment

 實體也是一對多關系. 也就是說一個學生可以注冊多門課程,一門課程允許多位學生注冊。

為每個實體建立對應的類:

注意:在完成所有實體之前嘗試編譯,将導緻編譯失敗.

Student Entity

MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

在Models檔案夾建立Student.cs ,代碼如下:

using System;
using System.Collections.Generic;

namespace ContosoUniversity.Models
{
    public class Student
    {
        public int StudentID { get; set; }
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
        public DateTime EnrollmentDate { get; set; }
        
        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
}      

StudentID

 屬性将成為資料表的主鍵列。預設Entity Framework将名為ID或者類名ID的屬性設為主鍵。

Enrollments

 是一個導航屬性。導航屬性記錄和本實體相關的其它實體。在本例中,

Enrollments

 屬性記錄和 

Student

 屬性相關的Enrollment。.如果資料庫中某

Student記錄和

兩條

Enrollment記錄

 相關。(這兩條記錄的 

StudentID

 外鍵值等于該Student的

StudentID)

 ,那麼

Student

 實體的 

Enrollments

 導航屬性将包含這兩個 

Enrollment

 實體.

Navigation properties 常定義為

virtual

 以便發揮Entity Framework的功能,如 lazy loading. (在 Reading Related Data 部分将詳細講述延遲加載).

如果navigation property 包含多記錄 (如 many-to-many or one-to-many 關系), 類型最好是清單類型,如 

ICollection

.

The Enrollment Entity

MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

在Models檔案夾, 建立 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; }
    }
}      

Grade類型

 後面的問号表示

Grade

 屬性是 nullable.

StudentID

 property 是外鍵, 相應的導航屬性是 

Student

.一個 

Enrollment

實體和一個 

Student

實體相關, 

CourseID

 property是外鍵, 相應的導航屬性是 

Course

The Course Entity

MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

在Models檔案夾, 建立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; }
    }
}      

Enrollments

 屬性是導航屬性. 一個 

Course

實體對應多個 

Enrollment

實體.

下一節再對 

[DatabaseGenerated(DatabaseGeneratedOption.None)] 

特性進行講解。 簡而言之,此特性表明主鍵由你指派而非資料庫自動生成。 

建立Database Context

将 Entity Framework 功能和給定資料模型相關聯的類是 database context class. 此類繼承自 System.Data.Entity.DbContext class.代碼表明資料模型包含了哪些實體類型.本項目中資料上下文類名為 

SchoolContext

.

建立 DAL檔案夾 (for Data Access Layer). 在此檔案夾建立SchoolContext.cs,代碼如下:

using ContosoUniversity.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace ContosoUniversity.DAL
{
    public class SchoolContext : DbContext
    {
        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>();
        }
    }
}      

代碼為每一個實體集合建立 DbSet 屬性。. 在Entity Framework,實體集合對應資料表,一個實體對應表中的一條記錄。.

modelBuilder.Conventions.Remove

 語句阻止表名使用實體的複數形式,如果沒有此語句,則生成的資料表分别是  

Students

Courses

, and

Enrollments

. 使用此語句,表名将和實體名一樣 

Student

Course

, and 

Enrollment

. 這和程式設計風格相關,至于是否使用複數取決于你自己。

SQL Server Express LocalDB

LocalDB 是一個輕量級的SQL Server。這裡不做翻譯介紹。

打開根目錄下的 Web.config 檔案,在 

connectionStrings

 處添加連接配接字元串如下,(注意,如果沒有localdb,而使用SQL Server或者Express版本,請修改連接配接字元串)

<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\ContosoUniversity.mdf" providerName="System.Data.SqlClient" />      

預設Entity Framework尋找和資料上下文類同名的連接配接字元串 (

SchoolContext

 for this project). 更多連接配接字元串資訊,請檢視 SQL Server Connection Strings for ASP.NET Web Applications.

也可不添加連接配接字元串,由程式自動生成。但會導緻資料庫檔案沒有放在程式的 App_data檔案夾下,更多資訊請檢視  Code First to a New Database.

connectionStrings

 集合預設包含一個名為 

DefaultConnection的連接配接字元串,是用來連接配接

  membership database. 這裡不會用到。兩條連接配接字元串唯一不同之處是資料庫名字不同

設定并執行 Code First Migration

在程式初期,資料模型經常發生變動,每次變動就會導緻和資料庫不一緻。可将Entity Framework配置為變動後自動重建資料庫。但在程式使用之後如果發生變動,更希望是更新資料庫而非重建(重建導緻資料丢失)。 Migrations 功能使得代碼優先方式下更新資料庫。如果希望重建可使用DropCreateDatabaseIfModelChanges實作每次變動後重建資料庫。.  本例中我們直接使用Migration方法,更多資訊請檢視 Code First Migrations.

啟用Code First Migrations

  1. 工具菜單,選擇Library Package Manager ,Package Manager Console.
    MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)
  2. PM>

     提示符下輸入如下指令:
    enable-migrations -contexttypename SchoolContext      
    MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)
    指令将建立 Migrations檔案夾,并在檔案夾下建立Configuration.cs.
    MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

    Configuration

     類包含 

    Seed

     方法,資料庫建立或更新後将調用此方法。
    internal sealed class Configuration : DbMigrationsConfiguration<ContosoUniversity.Models.SchoolContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }
    
        protected override void Seed(ContosoUniversity.Models.SchoolContext context)
        {
            //  This method will be called after migrating to the latest version.
    
            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }      

    Seed

     方法使得可設定自動插入到資料庫中的資料

設定Seed方法

為了便于測試,我們在Seed中添加一些資料

  1. 替換 Configuration.cs内容如下: 
    namespace ContosoUniversity.Migrations
    {
       using System;
       using System.Collections.Generic;
       using System.Data.Entity.Migrations;
       using System.Linq;
       using ContosoUniversity.Models;
    
       internal sealed class Configuration : DbMigrationsConfiguration<ContosoUniversity.DAL.SchoolContext>
       {
          public Configuration()
          {
             AutomaticMigrationsEnabled = false;
          }
    
          protected override void Seed(ContosoUniversity.DAL.SchoolContext context)
          {
             var students = new List<Student>
                {
                    new Student { FirstMidName = "Carson",   LastName = "Alexander", 
                        EnrollmentDate = DateTime.Parse("2010-09-01") },
                    new Student { FirstMidName = "Meredith", LastName = "Alonso",    
                        EnrollmentDate = DateTime.Parse("2012-09-01") },
                    new Student { FirstMidName = "Arturo",   LastName = "Anand",     
                        EnrollmentDate = DateTime.Parse("2013-09-01") },
                    new Student { FirstMidName = "Gytis",    LastName = "Barzdukas", 
                        EnrollmentDate = DateTime.Parse("2012-09-01") },
                    new Student { FirstMidName = "Yan",      LastName = "Li",        
                        EnrollmentDate = DateTime.Parse("2012-09-01") },
                    new Student { FirstMidName = "Peggy",    LastName = "Justice",   
                        EnrollmentDate = DateTime.Parse("2011-09-01") },
                    new Student { FirstMidName = "Laura",    LastName = "Norman",    
                        EnrollmentDate = DateTime.Parse("2013-09-01") },
                    new Student { FirstMidName = "Nino",     LastName = "Olivetto",  
                        EnrollmentDate = DateTime.Parse("2005-08-11") }
                };
             students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, 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.AddOrUpdate(p => p.Title, s));
             context.SaveChanges();
    
             var enrollments = new List<Enrollment>
                {
                    new Enrollment { 
                        StudentID = students.Single(s => s.LastName == "Alexander").StudentID, 
                        CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID, 
                        Grade = Grade.A 
                    },
                     new Enrollment { 
                        StudentID = students.Single(s => s.LastName == "Alexander").StudentID,
                        CourseID = courses.Single(c => c.Title == "Microeconomics" ).CourseID, 
                        Grade = Grade.C 
                     },                            
                     new Enrollment { 
                        StudentID = students.Single(s => s.LastName == "Alexander").StudentID,
                        CourseID = courses.Single(c => c.Title == "Macroeconomics" ).CourseID, 
                        Grade = Grade.B
                     },
                     new Enrollment { 
                         StudentID = students.Single(s => s.LastName == "Alonso").StudentID,
                        CourseID = courses.Single(c => c.Title == "Calculus" ).CourseID, 
                        Grade = Grade.B 
                     },
                     new Enrollment { 
                         StudentID = students.Single(s => s.LastName == "Alonso").StudentID,
                        CourseID = courses.Single(c => c.Title == "Trigonometry" ).CourseID, 
                        Grade = Grade.B 
                     },
                     new Enrollment {
                        StudentID = students.Single(s => s.LastName == "Alonso").StudentID,
                        CourseID = courses.Single(c => c.Title == "Composition" ).CourseID, 
                        Grade = Grade.B 
                     },
                     new Enrollment { 
                        StudentID = students.Single(s => s.LastName == "Anand").StudentID,
                        CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID
                     },
                     new Enrollment { 
                        StudentID = students.Single(s => s.LastName == "Anand").StudentID,
                        CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID,
                        Grade = Grade.B         
                     },
                    new Enrollment { 
                        StudentID = students.Single(s => s.LastName == "Barzdukas").StudentID,
                        CourseID = courses.Single(c => c.Title == "Chemistry").CourseID,
                        Grade = Grade.B         
                     },
                     new Enrollment { 
                        StudentID = students.Single(s => s.LastName == "Li").StudentID,
                        CourseID = courses.Single(c => c.Title == "Composition").CourseID,
                        Grade = Grade.B         
                     },
                     new Enrollment { 
                        StudentID = students.Single(s => s.LastName == "Justice").StudentID,
                        CourseID = courses.Single(c => c.Title == "Literature").CourseID,
                        Grade = Grade.B         
                     }
                };
    
             foreach (Enrollment e in enrollments)
             {
                var enrollmentInDataBase = context.Enrollments.Where(
                    s =>
                         s.Student.StudentID == e.StudentID &&
                         s.Course.CourseID == e.CourseID).SingleOrDefault();
                if (enrollmentInDataBase == null)
                {
                   context.Enrollments.Add(e);
                }
             }
             context.SaveChanges();
          }
       }
    }      
    由于此方法在建立或更新後調用,為了避免多次插入同一資料,調用AddOrUpdate方法,第一個參數用來檢查資料是否已經存在。
    context.Students.AddOrUpdate(p => p.LastName, s)      
    關于更多AddOrUpdate資訊,請檢視 Take care with EF 4.3 AddOrUpdate Method .
    foreach (Enrollment e in enrollments)
    {
        var enrollmentInDataBase = context.Enrollments.Where(
            s => s.Student.StudentID == e.Student.StudentID &&
                 s.Course.CourseID == e.Course.CourseID).SingleOrDefault();
        if (enrollmentInDataBase == null)
        {
            context.Enrollments.Add(e);
        }
    }      
    關于Seed中問題的調試,請檢視 Seeding and Debugging Entity Framework (EF) DBs . 
  2. 編譯.

建立并執行 First Migration

  1. 在 the Package Manager Console 執行指令: 
    add-migration InitialCreate
    update-database      
    MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

    add-migration

     指令将添加 [DateStamp]_InitialCreate.cs 檔案到Migrations檔案夾,檔案中包含資料庫建立初始化資訊。第一個參數 (

    InitialCreate)

     作為檔案名,前面會加上時間戳.
    MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

    InitialCreate 

    檔案代碼如下:
    namespace ContosoUniversity.Migrations
    {
        using System;
        using System.Data.Entity.Migrations;
        
        public partial class InitialCreate : DbMigration
        {
            public override void Up()
            {
                CreateTable(
                    "dbo.Student",
                    c => new
                        {
                            StudentID = c.Int(nullable: false, identity: true),
                            LastName = c.String(),
                            FirstMidName = c.String(),
                            EnrollmentDate = c.DateTime(nullable: false),
                        })
                    .PrimaryKey(t => t.StudentID);
                
                CreateTable(
                    "dbo.Enrollment",
                    c => new
                        {
                            EnrollmentID = c.Int(nullable: false, identity: true),
                            CourseID = c.Int(nullable: false),
                            StudentID = c.Int(nullable: false),
                            Grade = c.Int(),
                        })
                    .PrimaryKey(t => t.EnrollmentID)
                    .ForeignKey("dbo.Course", t => t.CourseID, cascadeDelete: true)
                    .ForeignKey("dbo.Student", t => t.StudentID, cascadeDelete: true)
                    .Index(t => t.CourseID)
                    .Index(t => t.StudentID);
                
                CreateTable(
                    "dbo.Course",
                    c => new
                        {
                            CourseID = c.Int(nullable: false),
                            Title = c.String(),
                            Credits = c.Int(nullable: false),
                        })
                    .PrimaryKey(t => t.CourseID);
                
            }
            
            public override void Down()
            {
                DropIndex("dbo.Enrollment", new[] { "StudentID" });
                DropIndex("dbo.Enrollment", new[] { "CourseID" });
                DropForeignKey("dbo.Enrollment", "StudentID", "dbo.Student");
                DropForeignKey("dbo.Enrollment", "CourseID", "dbo.Course");
                DropTable("dbo.Course");
                DropTable("dbo.Enrollment");
                DropTable("dbo.Student");
            }
        }
    }      
    The 

    update-database

     運作檔案中的 

    Up

     方法建立資料庫,然後調用 

    Seed

    方法.

名為 ContosoUniversity的資料庫将被建立,  .mdf檔案被存放在 App_Data 檔案夾,如你在連接配接字元串指定的一緻.

以下步驟是在VS中檢視資料庫的操作,按圖所示操作即可,不再翻譯。

  1. From the View menu, click Server Explorer.
  2. Click the Add Connection icon.
    MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)
  3. If you are prompted with the Choose Data Source dialog, click Microsoft SQL Server, and then clickContinue.
    MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)
  4. In the Add Connection dialog box,  enter  (localdb)\v11.0 for the Server Name. Under Select or enter a database name, select ContosoUniversity.
    MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)
  5. Click OK.
  6. Expand  SchoolContext and then expand Tables.
    MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)
  7. Right-click the Student table and click Show Table Data to see the columns that were created and the rows that were inserted into the table.
    MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

建立Student Controller and Views

  1. 右擊Controllers檔案夾,選擇建立Controller,相關參數資訊如下圖所示:
    MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)
  2. Visual Studio 打開 Controllers\StudentController.cs file. 資料庫上下文對象已經建立
    private SchoolContext db = new SchoolContext();      

    Index

     action method 從資料庫上下文擷取 

    Students

    屬性,傳回學生清單:
    public ViewResult Index()
    {
        return View(db.Students.ToList());
    }      
    The Student\Index.cshtml 視圖顯示了清單中的資訊:
    <table>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.LastName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.FirstMidName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EnrollmentDate)
            </th>
            <th></th>
        </tr>
    
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FirstMidName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EnrollmentDate)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.StudentID }) |
                @Html.ActionLink("Details", "Details", new { id=item.StudentID }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.StudentID })
            </td>
        </tr>
    }      
  3. Press CTRL+F5 運作。

    點選Students 檢視。

    MVC中使用EF(1):為ASP.NET MVC程式建立Entity Framework資料模型 為ASP.NET MVC程式建立Entity Framework資料模型 (1 of 10)

慣例

EF的這些慣例,使得以上所寫代碼不多:

  • 實體類名的複數形式作為表名.
  • 實體類的屬性名作為表的列名.
  • ID

     或 classname

    ID

     作為主鍵. 

慣例可以不必遵守(如本文不用複數形式作為表名),如果使用慣例或者覆寫慣例,請檢視後面的 Creating a More Complex Data Model 。更多資訊請檢視. Code First Conventions.

總結

使用 Entity Framework 和SQL Server Express 建立了一個簡單的web程式。随後将學習如何完成基本的 CRUD (create, read, update, delete) 操作.

繼續閱讀