溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用EF?Code?First搭建ASP.NET?MVC網(wǎng)站并允許數(shù)據(jù)庫遷移

發(fā)布時間:2022-10-20 14:59:26 來源:億速云 閱讀:113 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了如何使用EF Code First搭建ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫遷移的相關(guān)知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇如何使用EF Code First搭建ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫遷移文章都會有所收獲,下面我們一起來看看吧。

創(chuàng)建一個ASP.NET MVC 4 網(wǎng)站。

在Models文件夾內(nèi)創(chuàng)建Person類。

    public class Person
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

在Controls文件夾內(nèi)創(chuàng)建PersonController,選擇使用Entity Framework的模版、模型類,創(chuàng)建數(shù)據(jù)上下文類,如下:

如何使用EF?Code?First搭建ASP.NET?MVC網(wǎng)站并允許數(shù)據(jù)庫遷移

點擊"添加"后,除了在Controls文件夾內(nèi)多了PersonController,在Models文件夾中多了PersonContext類,如下:

using System.Data.Entity;
namespace MvcApplication1.Models
{
    public class PersonContext : DbContext
    {
        // 您可以向此文件中添加自定義代碼。更改不會被覆蓋。
        // 
        // 如果您希望只要更改模型架構(gòu),Entity Framework
        // 就會自動刪除并重新生成數(shù)據(jù)庫,則將以下
        // 代碼添加到 Global.asax 文件中的 Application_Start 方法。
        // 注意: 這將在每次更改模型時銷毀并重新創(chuàng)建數(shù)據(jù)庫。
        // 
        // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<MvcApplication1.Models.PersonContext>());
        public PersonContext() : base("name=PersonContext")
        {
        }
        public DbSet<Person> People { get; set; }
    }
}

在Web.config中的connectionStrings多了如下配置,選擇了默認的localdb數(shù)據(jù)庫。

  <connectionStrings>
    ......
    <add name="PersonContext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=PersonContext-20150210155119; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|PersonContext-20150210155119.mdf"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

在Views/文件夾中多了Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, Index.cshtml這個幾個視圖文件。

現(xiàn)在,我們想啟動EF的自動遷移功能。點擊"工具"-"庫程序包管理器"-"程序包管理器控制臺",輸入enable-migrations:

如何使用EF?Code?First搭建ASP.NET?MVC網(wǎng)站并允許數(shù)據(jù)庫遷移

在根目錄下多了一個Migrations文件夾,以及生成了一個Configuration類,如下:

namespace MvcApplication1.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    internal sealed class Configuration : DbMigrationsConfiguration<MvcApplication1.Models.PersonContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }
        protected override void Seed(MvcApplication1.Models.PersonContext 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" }
            //    );
            //
        }
    }
}

以上,我們可以添加一些種子數(shù)據(jù)。

現(xiàn)在需要把種子數(shù)據(jù)遷移到數(shù)據(jù)庫,在"程序包管理器控制臺",輸入add-migration initial

如何使用EF?Code?First搭建ASP.NET?MVC網(wǎng)站并允許數(shù)據(jù)庫遷移

此時,在Migrations文件夾內(nèi)多了201502100756322_initial類,記錄了本次遷移的動作。

namespace MvcApplication1.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class initial : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.People",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        FirstName = c.String(),
                        LastName = c.String(),
                    })
                .PrimaryKey(t => t.ID);
            
        }
        
        public override void Down()
        {
            DropTable("dbo.People");
        }
    }
}

最后別忘了要更新數(shù)據(jù)庫,在"程序包管理器控制臺",輸入update-database:

如何使用EF?Code?First搭建ASP.NET?MVC網(wǎng)站并允許數(shù)據(jù)庫遷移

這時候,瀏覽/Person/Index,能實現(xiàn)所有的增刪改功能。

如果這時候,我們希望在Person中增加一個屬性,比如類型為int的Age屬性。

    public class Person
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }

我們?nèi)绾胃嬖V數(shù)據(jù)庫呢?

還是在"程序包管理器控制臺",輸入add-migration 名稱

如何使用EF?Code?First搭建ASP.NET?MVC網(wǎng)站并允許數(shù)據(jù)庫遷移

此時,在Migrations文件夾內(nèi)多了201502100812315_addedage類,記錄了本次遷移的動作。

最后,還在"程序包管理器控制臺",輸入update-database以更新數(shù)據(jù)庫。

如何使用EF?Code?First搭建ASP.NET?MVC網(wǎng)站并允許數(shù)據(jù)庫遷移

為了讓視圖與當前Person類同步,可以先后刪除Person文件夾和PersonController控制器,再重新創(chuàng)建PersonController控制器,選擇使用Entity Framework的模版、Person類,PersonContext上下文類。

關(guān)于“如何使用EF Code First搭建ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫遷移”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“如何使用EF Code First搭建ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫遷移”知識都有一定的了解,大家如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI