EF CodeFirst 創建數據庫


CodeFirst 用中文說是代碼優先,此技術可以讓我們先寫代碼,然后由Entity Framework根據我們的代碼建立數據庫

接下來用學生這個例子來演示,有學生表,課程表,和成績表三張表

首先是Model層

學生表

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/**/
using System.ComponentModel.DataAnnotations;//驗證

namespace CodeFirstDemo.Models
{
    public class Student
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [StringLength(50)]
        public string Name { get; set; }
    }
}

課程表

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/**/
using System.ComponentModel.DataAnnotations;//驗證

namespace CodeFirstDemo.Models
{
    public class Course
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [StringLength(50)]
        public string Name { get; set; }
    }
}

成績表

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/**/
using System.ComponentModel.DataAnnotations;//驗證
namespace CodeFirstDemo.Models
{
    public class Score
    {
        [Key]
        public int Id { get; set; }

        public Student Student { get; set; }

        public Course Course { get; set; }

       
    }
}

[Key]表示在數據庫中該字段為主鍵,[Required]表示不為空,[StringLength]也就是長度了

這一步完成之后,我們要建立一個StudentInfoEntities的類,這個類要繼承自DbContext,而DbContext類在System.Data.Entity命名空間下,需引用EntityFramework.dll類庫,

如安裝不了,可以去Visual Studio Gallery下載,其實,只需要引用一個叫做Entity Framework的dll類庫即可

StudentInfoEntities類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/**/
using System.Data.Entity;

namespace CodeFirstDemo.Models
{
    public class StudentInfoEntities:DbContext
    {
        public DbSet<Course> Courses { get; set; }
        public DbSet<Score> Scores { get; set; }
        public DbSet<Student> Students { get; set; }
    }
}

接着,我們在Web.Config里配置一下數據庫的連接字符串

  <connectionStrings>
    <add name="StudentInfoEntities" connectionString="Data Source=.\SQLEXPRESS; User=test;Password=test;Initial Catalog=StudentInfo;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

 

最后,新建一個HomeController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
/**/
using CodeFirstDemo.Models;
namespace CodeFirstDemo.Controllers
{
    public class HomeController : Controller
    {
        private StudentInfoEntities db = new StudentInfoEntities();
        public string Index()
        {
            var data = db.Students.ToList();
            return "Database is build success!";
        }

    }
}

點擊調試,觸發一下,查看數據庫

同時,您會發現,在Score表中,自動產生外鍵關系

 

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM