EF的代码优先模式(Code First)

543 阅读2分钟

好了,好了,话不多说,EF的思想啊介绍啊,请看上一篇:juejin.cn/post/684490…

一、开始创建我们的项目吧!

1、第一步,创建一个控制台应用程序,并且添加NuGet包“EntityFramework”。

2、第二步,建立一个班级类和一个学生类,是一对多的关系

  • “public virtual ICollection Student { get; set; }”表示一个班有多个学生, 通过“ public virtual Class Class { get; set; }”,来表示学生都是班级里的一个,这样就体现了,一对多的关系
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class Class
    {
        public int Id { get; set; }
        public string ClassName { get; set; }
        public virtual ICollection<Student> Student { get; set; }//代表的意思是一个班级有很多个学生
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class Student
    {
        public int Id { get; set; }
        public string StuName { get; set; }
        public virtual Class Class { get; set; } //表示学生是班级的
    }
}

3、第三步,我们在以前使用EF的时候是不是都有上下文??。所以我们来建立一个上下文类。

  • 要继承基类,DbContext,所有我们要添加对“using System.Data.Entity;”的引用,如果你没有的话,进行第一步,安装“Entity Framewor”,并且右键添加引用。
  • 建立一个构造函数,并且指定连接字符串的名字“: base("conStr")”,使用daset绑定实体类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace ConsoleApp1
{
    public class DbTextContext:DbContext
    {
        public DbTextContext(): base("conStr")
        {

        }
        public DbSet<Class> Classe { get; set; }
        public DbSet<Student> Student { get; set; }
    }
}


4、接下来我们就配置我们的连接字符串,在App.config里添加如下代码

  <connectionStrings>
    <add name="conStr" connectionString="data source=.;initial catalog=数据库名写你要创建的;persist security info=True;user id=xx;password=xxxxxx;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>

5、好了,我们的基本配置已经完成了,在main里写以下,代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (DbTextContext db = new DbTextContext())
            {
                //创建数据库,没有就创建
                db.Database.CreateIfNotExists();
                db.SaveChanges();
            }
        }
    }
}

第六步,好了,这样我们的数据库,就已经创建好了,表的主外键也好了,不相信??自己打打去看看吧。另外,我们发现建立的表后都有s,怎么去掉呢?,在上下文添加

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();  //将映射成的表移除复数约定,不加s
        }


一些关于上下文的配置:www.cnblogs.com/libingql/p/…

结束语:你身后是你挚爱的人啊!加油!