First recommend a good EF article translation, you can learn the system again.
"Entity Framework 6 Recipes" Chinese Translation series
Benefits of EF Use:
- You can save ADO from complicated pipe connection code.
- The connection and development of the database can be accomplished by simple reference.
- You can save some SQL statements, and some of the underlying may need to adapt to a multi-database to provide some convenience.
Disadvantages:
- High learning costs, if you do not understand SQL, the index of some database knowledge, but also write a relatively optimized LINQ query, all EF to understand both SQL and LINQ is the best.
- Relatively large, the DLL for EF is connected to SQL Server by default to connect other databases that reference other databases with DLLs that add up to 10 m, and a lightweight framework like dapper is more than 100 K.
- The query supports only the conversion of data results to entities, and does not support DataTable.
Data Summary EF Connection
Multiple ways to connect to a database
EF Configuration
EF's domineering configuration seconds kill everything
EF advanced 1. Learn LINQ to SQL
LINQ to SQL Syntax rollup
2. Learn Expression
LINQ Expression Advanced Article
3. Optimization test
EF query performance test for millions data
A simple class library
Project
Data.map related Entitytypeconfiguration
Related entities in Data.module
Here's the Efcontext and Efdatabase class.
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 database configuration public class Efcontext:dbcontext, I Disposable {public Efcontext (string dbName): Base (dbName) {Database.setinitializ Er<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>///return character set//</summary>//<typeparam name= "tab Le "></typeparam>///<returns></returns> public dbset<table> set<table> () w Here Table:class {return dbcontext. Set<table> (); } #region Properties///<summary>//Get the currently used data access context object///</summary> public DBCO ntext DbContext {get; set;} <summary>///Transaction object///</summary> public dbtransaction dbtransaction {get; set;} #endregion #region Constructor PuBlic efdatabase (String database) {DbContext = new Efcontext (database); } #endregion #region Private method///<summary>//Get entity class Key value (cache)///</summary> <typeparam name= "T" ></typeparam>//<param name= "entity" ></param>//<re turns></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>///Stored Procedure statement///</summary>//<param name= "ProcName" &G t; stored procedure name </param>//<param name= "dbparameter" > SQL statement parameters required to execute command </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 entit Y in entities) {DbContext. Set<t> (). Attach (entity); DbContext. Set<t> (). Remove (entity); } return dbtransaction = = null? DbContext. SaveChanges (): 0; } #endregion Public Efdatabase BeginTrans () {DbConnection DbConnection = ((iobjectcontext Adapter) 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) {RET Urn 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, NE W () {return dbcontext. Set<t> (). Where (condition); } Public iqueryable<t> findlist<t> (string strSQL) where T:class {return Dbcon Text. 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 {Strin G 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 () = = " " | | 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 Framework Learning EF