Microsoft Enterprise Library 6 Data Access application Block Extension

Source: Internet
Author: User

Although the title is the extension to 6, in fact, for 4, 5 is also applicable, because the Enterprise Library in these versions did not change much

The extension is primarily for Dataaccessor<t>, where the class is to pass several interfaces when it is created: iparametermapper,irowmapper<t>,iresultsetmapper<t> The Irowmapper<t> Enterprise Library provides mapbuilder<t> static classes to assist in creating corresponding relationships, but for Iparametermapper and iresultsetmapper<t> Did not provide the ready-made class (perhaps, but I did not find, after all, did not study its source code)

The following is the specific code, the design idea is: Iparametermapper and iresultsetmapper<t> is actually to implement a contract method, and for this method, I directly set the general class, the class accepts the specific implementation of the delegate, The delegate is determined by coder, without the need for coder to create related classes repeatedly, reducing the amount of code

The PS:DbCommand.Parameters.AddRange accepts the DbParameter parameter, so the specific dbparameter can be passed directly

1, Generalparametermapper

    <summary>//General Iparametermapper///If the DbParameter to be passed before execute is already in use by another DbCommand, an exception will be generated///So the DBC should be called Ommand. Parameters.clear method frees other DbCommand for DbParameter//</summary> public class Generalparametermapper:iparameter        Mapper {private Action<dbcommand, object[]> _act;        <summary>//Generalparametermapper//</summary>/<param name= "Act" > Defines how to assign parametervalues to a DbCommand delegate///If not passed, the default delegate is used, which does not verify whether the parametervalues to be passed is defined in DbCommand//at this time repeatedly Executing execute will cause an exception to be guaranteed that it will not cause repeated queries due to encoding problems </param> public generalparametermapper (Action<dbcommand, object[]> AC            T = null) {if (act! = null) {this._act = act; } else {this._act = (cmd, paramters) = {CMD.P Arameters.                AddRange (paramters);            }; }} #region Iparametermapper members///<summary>//iparametermapper.assignparameters//</summary>        <param name= "command" ></param>//<param name= "ParameterValues" ></param> public void Assignparameters (DbCommand command, object[] parametervalues) {if (parametervalues! = null            && parametervalues.length > 0) {this._act (command, parametervalues); }} #endregion}
2, Generalresultsetmapper

    <summary>//General Iresultsetmapper//</summary>/<typeparam name= "T" ></typeparam&    Gt public class Generalresultsetmapper<t>: iresultsetmapper<t> {private Func<idatareader, T> _f        Unc <summary>//Generalresultsetmapper//</summary>/<param Name= "Func" > by ID Atareader How to return T delegate </param> public Generalresultsetmapper (Func<idatareader, t> Func) {i            F (func = = null) {throw new ArgumentNullException ();        } This._func = func; } #region iresultsetmapper<t> members//<summary>//iresultsetmapper.mapset//&lt ;/summary>//<param name= "reader" >IDataReader</param>///<returns>list collection, if Count is 0, the table No data is returned, no null value </returns> public ienumerable<t> mapset (IDataReader reader) {LIST&LT            t> list = new list<t> (); while (reader. Read ()) {list.            ADD (This._func (reader));        } return list; } #endregion}

On the basis of these two classes, but also encapsulated an extension class, specifically for the Microsoft Enterprise Library dataaccessor Extension, the following is the specific code, because of personal preferences, does not encapsulate the corresponding proc extension method, in fact, the code is the same

    <summary>///Microsoft Enterprise Library data Related Help class///</summary> public static class Entlibdbhelper {// <summary>////Bulk query SQL and AutoFill entities, if you do not need to pass dbparameter, we recommend that you do not use this method, you should use the Database.executesqlstringaccessor method//        </summary>//<typeparam name= "T" ></typeparam>//<param name= "DB" ></param> <param name= "SQL" ></param>///<param Name= "parametermapperaction" > Specify delegate confirmation on how SQL parameters to pass The value can pass NULL, which is NULL when the default delegate is used, and the delegate directly passes ParameterValues to the Cmd.Parameters.AddRange method </param>///<param name= " RowMapper "> indicates how EntLib fills T, and if not, it will be assigned by default by the properties of T </param>//<param name=" parametervalues "> the SQL parameter to be passed. This section corresponds to parametermapperaction</param>//<returns></returns> public static ilist<t> Ex Ecutebysqlstring<t> (This Database db, String sql, Action<dbcommand, object[]> parametermapperaction, Irowmapper<t> RowMapper = null, parAMS object[] parametervalues) where t:new () {if (RowMapper = = null) { RowMapper = Mapbuilder<t>.            Buildallproperties ();            } iparametermapper parametermapper = new Generalparametermapper (parametermapperaction); Return DB. createsqlstringaccessor<t> (SQL, Parametermapper, RowMapper). Execute (parametervalues).        ToList ();         }///<summary>///Bulk query SQL and AutoFill entities, if you do not need to pass dbparameter, we recommend that you do not use this method, you should use the Database.executesqlstringaccessor method </summary>//<typeparam name= "T" ></typeparam>//<param name= "DB" >&lt ;/param>//<param name= "SQL" ></param>///<param Name= "parametermapperaction" > Specify delegate Acknowledgement How the SQL parameter to pass is handled, the value can pass NULL when NULL is used, and the delegate directly passes ParameterValues to the Cmd.Parameters.AddRange method </param>///< param name= "Resultsetmapperfunc" > Instructions entlib how to populate t</param>//<param name= "paramEtervalues "> SQL parameter to pass, this section corresponds to parametermapperaction</param>///<returns></returns> Public Static ilist<t> executebysqlstring<t> (this Database db, String sql, Action<dbcommand, object[]>            Parametermapperaction, Func<idatareader, t> resultsetmapperfunc, params object[] parametervalues) {            Iparametermapper parametermapper = new Generalparametermapper (parametermapperaction);            iresultsetmapper<t> resultsetmapper = new generalresultsetmapper<t> (RESULTSETMAPPERFUNC); Return DB. createsqlstringaccessor<t> (SQL, Parametermapper, resultsetmapper). Execute (parametervalues).        ToList (); }    }
Incidentally, add a generic data extension

    <summary>///data Related Help class///</summary> public static class DBHelper {//<summar         Y>///Read nullable objects from DataReader///</summary>//<typeparam name= "T" > Generics t</typeparam> <param name= "Dr" >IDataReader</param>//<param name= "key" >Key</param>/  <returns></returns> public static nullable<t> getnullable<t> (This IDataRecord dr, string Key) where t:struct {return Dr[key] = = NULL | | dr[key] = = DBNull.Value?        (nullable<t>) Null: (T) Dr[key]; }///<summary>//When DataReader read object is empty, return defaultvalue//</summary>//&LT;TYPEP Aram Name= "T" > Generics t</typeparam>//<param name= "Dr" >IDataReader</param>//<param NA      Me= "key" >Key</param>///<param Name= "DefaultValue" > when the data is DBNull, the default value should be returned </param>  <returns></returns> public static T-getdefaultwhilenullable<t> (This IDataRecord dr, string Key, T defaultvalue = Default (t)) {return Dr[key] = = NULL | | dr[key] = = DBNull.Value? DefaultValue: (        T) Dr[key]; }///<summary>//Read the string from DataReader and specifier//</summary>//<param name= " Dr ">IDataReader</param>//<param name=" key ">Key</param>//<returns></retur ns> public static string gettrimedstring (this IDataRecord dr, string key) {return Dr[key]. ToString ().        Trim (); }    }

The following code is used:

String sql = @ "SELECT [Pdate], [Pbegtime], [Pendtime], [PID], [Pdateid] from Tbltime with (NOLOCK) WHERE            [Email protected] "; irowmapper<product> rowmapper = Mapbuilder<product>. Mapnoproperties (). Map (p = p.id). Tocolumn ("Pdateid"). Map (p = p.name). Withfunc ((dr) = = {return string. Format ("{0}-{1}", Dr. Gettrimedstring ("Pbegtime"), Dr.                Gettrimedstring ("Pendtime")); })                .            Build (); var list = db.            executebysqlstring (SQL, NULL, RowMapper, new SqlParameter ("@PID", 12345) {DbType = dbtype.int32}); MessageBox.Show (list.            Count.tostring ());            Iparametermapper paramtermapper = new Generalparametermapper (); var _productaccessor = db.            Createsqlstringaccessor (SQL, Paramtermapper, rowmapper); var products = _productaccessor.execute (new SqlParameter ("@PID", 12345) {DbType = Dbtype.int32}).        ToList ();    if (products! = null && products. Count > 0) {MessageBox.Show (products).            Count.tostring ()); }


Microsoft Enterprise Library 6 Data Access application Block Extension

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.