MVC學習之 Code First

來源:互聯網
上載者:User

標籤:style   blog   io   ar   color   sp   on   檔案   資料   

Code First 代碼優先。

上代碼:

建立你需要的資料模型(也可以認為是你需要的資料表):

namespace CodeFirstDemo.Models{    public class Student    {        public int Id { get; set; }        public string Name { get; set; }    }    public class Teacher    {        public int Id { get; set; }        public string Name { get; set; }    }}


建立CodeFirstDB類,繼承自DbContext類。(注意引入System.Data.Entity命名空間的引用):

namespace CodeFirstDemo.Models{    public class CodeFirstDB:DbContext    {        public DbSet<Student> Student { get; set; }        public DbSet<Teacher> Teacher { get; set; }    }}

 

資料庫建立:

1.播種資料庫。

2.為了保證資料庫與模型同步(暫不考慮資料移轉的問題),在程式啟動每次啟動時重新建立資料庫(僅當檢測到模型改變時建立)

 

 protected void Application_Start()        {            //當程式每次啟動時,檢測到模型改變則重新建立資料庫            Database.SetInitializer(new CodeFirstDemo());                        AreaRegistration.RegisterAllAreas();            WebApiConfig.Register(GlobalConfiguration.Configuration);            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);            RouteConfig.RegisterRoutes(RouteTable.Routes);            BundleConfig.RegisterBundles(BundleTable.Bundles);            AuthConfig.RegisterAuth();        }
  /// <summary>    /// 播種資料庫    /// </summary>    public class CodeFirstDemo : DropCreateDatabaseAlways<CodeFirstDB>    {        protected override void Seed(CodeFirstDB context)        {            context.Student.Add(new Student { Id = 1, Name = "小明" });            context.Teacher.Add(new Teacher { Id = 1, Name = "老王" });            base.Seed(context);        }    }

程式調用:

 public ActionResult Index()        {            CodeFirstDB db = new CodeFirstDB();            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";            var data = db.Student.ToList();            return View();        }

調用完成後,在你的App_Data檔案夾中查看結果。

注意:如果要為欄位賦值預設值。在預設建構函式中進行。

MVC學習之 Code First

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.