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

好了,好了,话很少说,EF的思想啊介绍啊,请看上一篇:juejin.im/post/5d99d0…html

1、开始建立咱们的项目吧!

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

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

  • “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; } //表示学生是班级的
    }
}

复制代码

三、第三步,咱们在之前使用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; }
    }
}


复制代码

四、接下来咱们就配置咱们的链接字符串,在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>
复制代码

五、好了,咱们的基本配置已经完成了,在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/…数据库

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

相关文章
相关标签/搜索