Entity Framework(EF的Code First方法)

EntityFramework,是Microsoft的一款ORM(Object-Relation-Mapping)框架。同其它ORM(如,NHibernate,Hibernate)同样,数据库

一是为了使开发人员以操做对象的方式去操做关系型数据表。app

二是为了屏蔽底层不一样厂商的数据库,开发人员面向ORM框架编写数据的CRUD(Create,Retrieve,Update,Delete)操做,再由ORM框架将这些操做翻译成不一样数据库厂商的语言。框架

从EF 4.X开始支持三种构建方法:1. Database First方法。2.Model First方法。3.Code First 方法。ide

本次测试以Visual Studio2013 / MS Sql Server2012 / Entity Framework 6.X 测试EF 工具

Code First Demo此时数据库和表格都已经存在,为了在原有项目中引入EF,须要使用这种方式测试

关键:上下文,实体类的约束及关系this

//MS SQL Server链接字符串 
//connectionString="Data Source=(local);Initial Catalog=EFTest;User Id=sa;Password=123456;" providerName="System.Data.SqlClient"
<connectionStrings>
  <add name="EFTest" connectionString="Data Source=(local);Initial Catalog=EFTest;User Id=sa;Password=123456;" providerName="System.Data.SqlClient"></add>
</connectionStrings>

原有项目中,已经有了模型类,因此再也不从新生成模型类spa

操做步骤:翻译

 1>引入程序集EntityFramework.dll,System.Data.Entity.dll3d

 2>在配置文件中 写链接字符串

 3>建立模型类(若是项目中有模型类,则只须要维护关系)

     经过导航属性来表示类的关系,注意:导航属性设置成virtual,

     特性维护:Table,Key,ForeignKey

 4>建立上下文类,继承自DbContext

     调用父类构造方法,传递链接字符串"name=***"

 5>根据类型建立数据库表

     Context1 context = new Context1();

     使用context.Database.CreateIfNotExists();完成数据库中表的建立;

     调用context.SaveChanges()方法完成保存。

1:打开SQLServer2012,使用下面SQL文本建立MyFirstModelFirstEF数据库

create database EFTest
on primary
(
    name='EFTest.mdf',
    --修改成本身电脑上SQL DB路径
    filename='D:\yangZ_MSSQL\EFTest.mdf',
    size=5mb,
    maxsize=100mb,
    filegrowth=10%
)
log on
(
    name='EFTest_log.ldf',
    --修改成本身电脑上SQL DB路径
    filename='D:\yangZ_MSSQL\EFTest_log.ldf',
    size=2mb,
    maxsize=100mb,
    filegrowth=5mb
)
go

2:新建ConsoleApplication应用程序EFCodeFirstDemo

3:引入程序集EntityFramework.dll,System.Data.Entity.dll (默认找不到引用EntityFramework.dll)

 3.1:能够经过NuGet来获取 [工具-->库程序包管理器-->程序包管理器控制台],Ps:这种方式要求电脑必须联网

Install-Package EntityFramework -Version 6.0.2
Install-Package EntityFramework -Pre (表示最新)
Uninstall-Package EntityFramework -Version 6.1.0

 3.2:拷贝现有EF项目中的EntityFramework.dll文件

 3.3:能够经过ModelFirst/DatabaseFirst(不添加任何表格)引入dll,而后删除Model.edmx文件

在EFCodeFirstDemo上 右键-->新建-->新建项-->数据-->ADO.NET实体数据模型,选择从数据库生成/空模型,而后点击完成

4:在配置文件中 写链接字符串

  <connectionStrings>
    <add name="EFTest" connectionString="Data Source=(local);Initial Catalog=EFTest;User Id=sa;Password=123456;" providerName="System.Data.SqlClient"></add>
  </connectionStrings>

5:建立模型类(若是项目中有模型类,则只须要维护关系)

     经过导航属性来表示类的关系,注意:导航属性设置成virtual,

     特性维护:Table,Key,ForeignKey

ContactInfo.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCodeFirstDemo
{
    //Table是在 System.ComponentModel.DataAnnotations.Schema
    [Table("ContactInfo")]
    public class ContactInfo
    {
        //Key 是在System.ComponentModel.DataAnnotations
        [Key]
        public int InfoId { get; set; }

        public string InfoName { get; set; }

        //ForeignKey  是在System.ComponentModel.DataAnnotations.Schema
        [ForeignKey("ContactType")]
        public int ContactTypeId { get; set; }

        public virtual ContactType ContactType { get; set; }
    }
}

ContactType.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCodeFirstDemo
{
    //Table是在 System.ComponentModel.DataAnnotations.Schema
    [Table("ContactType")]
    public class ContactType
    {
        public ContactType()
        {
            this.ContactInfo = new HashSet<ContactInfo>();
        }

        //Key 是在System.ComponentModel.DataAnnotations
        [Key]
        public int TypeId { get; set; }

        public string TypeTitle { get; set; }

        public virtual ICollection<ContactInfo> ContactInfo { get; set; }
    }
}

经过实体框架 Code First 创建新数据库 连接: http://pan.baidu.com/s/1qYBZiCc  密码: 5r4a

6:建立上下文类,继承自DbContext

     调用父类构造方法,传递链接字符串"name=***"

 6.1:在EFCodeFirstDemo project项目 右键-->添加-->类 Context1.cs

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

namespace EFCodeFirstDemo
{
    public class Context1 : DbContext
    {
        public Context1()
            : base("name=EFTest")
        {
        }

        public virtual DbSet<ContactType> ContactType { get; set; }

        public virtual DbSet<ContactInfo> ContactInfo { get; set; }
    }
}

7:根据类型建立数据库表

     Context1 context = new Context1();

     使用context.Database.CreateIfNotExists();完成数据库中表的建立;

     调用context.SaveChanges()方法完成保存。

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

namespace EFCodeFirstDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Context1 context = new Context1();
            //在现有连接数据库中 ,若当前实体模型对应的数据库不存在,则建立,反之则不须要建立
            context.Database.CreateIfNotExists();
            context.SaveChanges();
        }
    }
}

此时对应MS SQL Server数据库为:

 【未完,待续】

相关文章
相关标签/搜索