C# Code First 配置

來源:互聯網
上載者:User

標籤:frame   就會   png   oid   應用   ace   round   代碼   asd   

 

前言

所謂code first,是代碼優先,而不是傳統的資料庫優先。

code first的好處多多,可不用考慮資料庫,只考慮物件導向。下面我們介紹一下code first的配置。

 

開始

我們這裡以建立一個MVC的Code first為例,名字為MVCCodeFirst。

1)建立模型

建立一個資料的建立項,然後選擇ADO.NET實體資料模型,名字為MyModel

然後選擇Code First模型,空Code First模型,你也可以選擇來自資料庫的CodeFirst。我們這裡選擇空CodeFirst模型

確定之後,模型已經建立了

 

2)建立實體

我們建立一個實體School,有一個主鍵與學校名字

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Web;namespace MVCCodeFirst.Entity{    public class School    {        [Key]        public long Key { get; set; }        public string Name { get; set; }    }}

然後把School添加到DbContext的上下文中。

using System.ComponentModel.DataAnnotations;namespace MVCCodeFirst.Entity{    using System;    using System.Data.Entity;    using System.Linq;    public class MyModel : DbContext    {        public MyModel()            : base("name=MyModel")        {        }        //我們添加的School         public virtual DbSet<School> Schools { get; set; }    }}

 

3)啟動 Enable-Migrations

上面已經建立了表的實體,Code First要建立表,我們要通過命令列來自動產生SQL語句,所以要啟動這個功能。

在【封裝管理員控制台】中,啟動自動產生SQL語句

Enable-Migrations

如下:

完成之後,你在代碼裡面可以看到,自動添加了一個檔案夾為Migrations,並且類為Configuration.cs

開啟可以看到,這裡主要使用者初識化一些預設的資料

namespace MVCCodeFirst.Migrations{    using System;    using System.Data.Entity;    using System.Data.Entity.Migrations;    using System.Linq;    internal sealed class Configuration : DbMigrationsConfiguration<MVCCodeFirst.Entity.MyModel>    {        public Configuration()        {            AutomaticMigrationsEnabled = false;        }        protected override void Seed(MVCCodeFirst.Entity.MyModel context)        {            //初始化資料        }    }}

例如,我們可以初識化學校的資料。這個初始化資料是在輸入命令update-database的時候才會調用

//初始化資料格式context.Schools.AddOrUpdate(new School() {Key = 1, Name = "望牛墩中學"});context.SaveChanges();

 

4)設定資料庫

開啟web.config,可以看到資料庫連接現在是

<connectionStrings>    <add name="MyModel" connectionString="data source=(LocalDb)\MSSQLLocalDB;initial catalog=MVCCodeFirst.Entity.MyModel;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />  </connectionStrings>

我們修改成本地串連

<add name="MyModel" connectionString="Server=localhost; Database=MyModel; Trusted_Connection=True;" providerName="System.Data.SqlClient" />

 

5)用命令建立資料庫、表

初識化資料

add-migration init

就會產生建立的SQL類在Migrations檔案夾下

 

建立資料庫、表。在命令中輸入:

update-database

我們可以看到本機資料庫中有建立了此資料庫與表:

 

 

3.其他

1)果想指定表的名字,可以在實體類上用註解Table,例如

[Table("School")]public class School

 

2)主鍵註解 [Key]

[Key]public long Id { get; set; }

 

3)如果想建立一個自增長的主鍵

在DB上下文實體中,繼承OnModelCreating方法,並且實現實體的主鍵自增長

using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;namespace MVCCodeFirst.Entity{    using System;    using System.Data.Entity;    using System.Linq;    public class MyModel : DbContext    {        //您的上下文已配置為從您的應用程式的設定檔(App.config 或 Web.config)        //使用“MyModel”連接字串。預設情況下,此連接字串針對您的 LocalDb 執行個體上的        //“MVCCodeFirst.Entity.MyModel”資料庫。        //         //如果您想要針對其他資料庫和/或資料庫提供者,請在應用程式設定檔中修改“MyModel”        //連接字串。        public MyModel()            : base("name=MyModel")        {        }        //我們添加的Schools        public virtual DbSet<School> Schools { get; set; }        protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            //自增長主鍵            modelBuilder.Entity<School>()                .Property(o => o.Id)                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);        }    }}

C# 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.