Using basic knowledge to realize data to model filling

Source: Internet
Author: User

In the current development, we usually query the data from the database, and then fill the data into an object, and then it is convenient to read the object information.  Data to populate the object of the process is very cumbersome, in order to simplify the problem, various frameworks, components emerge in this list, I do not enumerate-_-! Many frameworks are convenient to use, but I always think of a word the original text is blurred, the source forgot, the effect is "when to a certain degree of technology will be in their own way failure", and do not say that failure does not fail, with the framework of the students at some point must have such a feeling: "If this framework to support XX is good", " This function is very simple, but our project is now using this framework, to achieve this function seems to write stand Eaves foot code "," This framework is increasingly not in line with our requirements, do we want to change to YY framework? Wait So the framework has its own inherent limitations, then we face the problem, the first time really have to turn to the framework?

This article would like to express no contempt of the meaning of the framework, but the park in the framework of a lot of discussion, often let novice have a kind of do not understand, do not use a certain frame to explain oneself a large section of the feeling, but also let a lot of beginners just because they will use a lot of frame feel very much the appearance of cow B, no matter what kind of situation, are not conducive to their own technical improvement. So this article is just hoping that the novice can think deeply about their own situation, give yourself a correct assessment, and try to see how to call, you can probably imagine how the interior is achieved, the white is very familiar with the language itself, some ideas have to understand, the following do not list the various frameworks, A technology that is known to beginners is a combination of data to object implementation.

Preparation and questions:

Prepare 1, Database test1 has table myuser{

ID (PK, int, not NULL)

UserName (varchar), NOT NULL

Age (tinyint, not NULL)

Birthday (datetime, NULL)

}

Prepare 2, Database test2 has table message{

ID (PK, int, not NULL)

myUserID (int, not NULL)

Content (nvarchar), NOT NULL

Addtime (datetime, NOT NULL)

}

Prepare to 3,sqlhelper One, this self needless to say, Access database!

Problem 1, a fill of data to object is implemented once, no matter how many fields are taken, whether it's a single data or multiple data

Question 2, associated query, in order to emphasize the demo, the associated data in different databases, the specific is to check the user and their message (may use dynamic and comments to illustrate more appropriate, hehe understanding!) )

Thinking:

Want to reuse, naturally will think of inheritance;

Want to unify processing, also want to think of abstraction;

Want to dynamically add data, to be able to think of a dictionary, we must remember that the dictionary is a very useful data structure;

If you want to use a uniform method to get different specific types of objects, it is natural to be generic.

The bottom will be reflected, now unclear so it doesn't matter.

Realize:

Data to the object of the fill, specific to ado.net, is generally reader to object, to implement dynamic fields are filled with a method, to MyUser, you can probably do this:

Public Messageinfo Fillmodelfromreader (DbDataReader reader, params string[] fields)
        {
            var info = new Messageinfo ();
            if (Dalutil.hasfields ("id", fields)) {info.id = (int) reader["id"];}
            if (Dalutil.hasfields ("myUserID", fields)) {info. myUserID = (int) reader["myUserID"]; }
            if (Dalutil.hasfields ("Content", fields)) {info. Content = reader["Content"]. ToString (); }
            if (Dalutil.hasfields ("Addtime", fields)) {info. Addtime = (DateTime) reader["Addtime"]; return
            info;
        }

Database interaction nothing more than those methods, we can abstract out a data access base class, in practical use also write several method overloads, in order to call

<summary>///dal base class///</summary>///<typeparam name= "T" ></typeparam> publi
        C Abstract class Dalbase<t> {///<summary>///subclasses decide which link to use///</summary>
        Protected abstract string Connname {get;
    
        Protected abstract T Fillmodelfromreader (DbDataReader reader, params string[] fields); Protected string Getconnstr () {return System.configuration.configurationmanager.connectionstrings[con Nname].
        ConnectionString;
            } protected list<t> Findlist (String sql, CommandType type, params sqlparameter[] parameters) {
                using (var reader = Sqlhelper.executereader (Getconnstr (), type, SQL, parameters)) {
                list<t> list = new list<t> ();
                var fields = dalutil.getreaderfieldnames (reader); while (reader.
Read ()) {                    List.
                ADD (Fillmodelfromreader (Reader, fields));
            } return list;
            } protected T FindOne (String sql, CommandType type, params sqlparameter[] parameters) { return findlist (SQL, type, parameters).
        FirstOrDefault (); Private list<t> Findpage (String tablename, string fields, string query, string by, int pageIndex , int pageSize, bool istotal, out int totalcount, params sqlparameter[] parameters) {if (PageIndex &L T
            1) {throw new ArgumentException ("pageindex parameter should be >1");
            StringBuilder sb = new StringBuilder ();
            Sqlparameter[] Newps; if (istotal) {sb.
                AppendFormat ("SELECT count (0) from [{0}]", tablename); if (!string. Isnullorwhitespace (query)) {sb. AppendFormat ("where {0}", query);
                } totalcount = GetCount (sb.
                ToString (), parameters); Sb.
                Clear ();
            Newps = sqlhelper.copyparameters (parameters);
                else {newps = parameters;
            TotalCount = 0; } if (string.
            Isnullorwhitespace (by) {throw new ArgumentException ("The By-order parameter should not be null"); var fs = string. Isnullorwhitespace (Fields)? "*": String.
            Join (",", fields); Sb.
            AppendFormat ("Select {0} from", FS); Sb. AppendFormat ("Select top {0} {1},row_number () 2}" rowID from {3} ", PageIndex * pageSize, FS, to order, tabl
            ENAME); if (!string. Isnullorwhitespace (query)) {sb.
            AppendFormat ("where {0}", query); } sb. AppendFormat (") t where t.rowid>{0} and T.rowid<={1}", (pageIndex-1) * pageSize, PageIndex * pageSize);
    
            Return Findlist (sb.)
        ToString (), CommandType.Text, newps);
            } Protected Object Getscalar (String sql, CommandType type, params sqlparameter[] parameters) {
        Return Sqlhelper.executescalar (Getconnstr (), type, SQL, parameters);
            protected int GetCount (String sql, CommandType type, params sqlparameter[] parameters) {
            var obj = getscalar (sql, type, parameters);
            if (obj = null) return-1;
        return (int) obj;
            protected int Execute (String sql, CommandType type, params sqlparameter[] parameters) {
        Return Sqlhelper.executenonquery (Getconnstr (), type, SQL, parameters); }
    }

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.