Entity Framework 是微软以 ADO.NET 为基础所发展出来的对象关系对应 (O/R Mapping) 解决方案
    对象关系映射(英语:Object Relational Mapping,简称ORM),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换。

 

    下载:Install-Package EntityFramework -Version 6.1.3  (7.0只有CodeOnly模式)

    本节技术概览:数据库的安装DB First,Model FirstCode First(重点)DbContext,DbSetCRUD例子数据迁移以及事务管理

 

LocalDB和SQL Server安装

  LocalDb是visual studio自带的,用来开发使用。运行是采用进程形式而非服务形式。

  位置:C:\Program Files\Microsoft SQL Server\110\Tools\Binn\SqlLocalDB.exe(这是vs 2013的位置,使用VS2013开发人员工具输入sqllocaldb即可)

  SQL Server采用服务方式,方便连接管理。可以去itellyou.cn下载。

连接

  可以直接用vs连接这2种数据库。连接localdb

[ORM] Entity Framework(1) CodeFirst快速入门

 

 

DB First,Model First

  [ORM] Entity Framework(1) CodeFirst快速入门

DB First采用通常的数据库先行的办法,常见,稳定。基本下一步下一步就能完成。

Model First在VS中 画模型图,来生成数据库和Object,不方便控制数据库。

这2个都会产生edmx文件(xml),包含SSDL(数据定义),CSDL(类定义),CS Mapping(数据类映射)

在edmx模型查看中,不会把所有表都显示。当2个表的关系为多对多的时候,关系表会由一条多对多的线来表示。

在Model Browser中,可以看到存储过程,视图等非表的信息。

 

CodeFirst

  在EF7中,只有Code Only 说明Code First的重要性。在使用中,中小型项目,我也推荐使用,毕竟开发效率提高了不止一点点。

 

创建POCO

    public class App
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<AppData> AppDatas { get; set; }
    }

    public class AppData
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Value { get; set; }
        public virtual App App { get; set; }
    }

 创建DbContext

    public class AppContext : DbContext
    {
        public AppContext()
            : base("AppDb")           //AppDb数据库库名
        {
            
        }
        public DbSet<App> Apps { get; set; }
        public DbSet<AppData> AppDatas { get; set; }
    }

文件结构:

[ORM] Entity Framework(1) CodeFirst快速入门

app.config

<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>
App.Config

相关文章: