Layim Project's basic Data acquisition code optimization, dapper replace ADO

Source: Internet
Author: User

Objective

Recently in the development of Layim cloud version, also in the project refactoring, and now look at the previous code, I simply dare not stare. But I do not know the future to see the code is not a bad batch. Layim has an interface, the general contact developers are not unfamiliar, is the Init interface. The data returned by the interface is probably Jiangzi:

1 {2"Code": 0,3"MSG": "",4"Data": {5"Mine": {6"username": "Paper Plane",7"id": "100000",8"Status": "Online",9"Sign": "In the deep coding world, make a light paper plane",Ten"Avatar": "/images/default.jpg" One         }, A"Friend": [ -             { -"GroupName": "Front-end code Dick", the"id": 1, -"Online": 2, -"List": [ -                     { +"username": "Yin Xin", -"id": "100001", +"Avatar": "/images/default.jpg", A"Sign": "These are the test data, the actual use please strictly follow the format returned" at                     }, -                     { -"username": "Z_ Fine", -"id": "108101", -"Avatar": "/images/default.jpg", -"Sign": "Micro e-commerce talent" in                     } -                 ] to             }, +             { -"GroupName": "Net Red", the"ID": 2, *"Online": 3, $"List": [Panax Notoginseng                     { -"username": "Luo Yufeng", the"id": "121286", +"Avatar": "/images/default.jpg", ASign: "Don't believe in media or reporters when you're not in your power." They are not good people, and sometimes their interviews are a trap for the parties. the                     }, +                     { -"username": "Long ze zi Azusa", $"id": "100001222", $"Sign": "I am a Japanese female artist, あずさ.", -"Avatar": "/images/default.jpg" -                     } the                 ] -             }Wuyi         ], the"Group": [ -             { Wu"GroupName": "Front end Group", -"id": "101", About"Avatar": "/images/default.jpg" $             }, -             { -"GroupName": "Fly Community official Group", -"id": "102", A"Avatar": "/images/default.jpg" +             } the         ] -     } $}
Layim init interface Data

In short, inside nested a lot of relations, for example, my friend group and friend's relationship, and some other data, in fact, careful analysis, will be conquer. Today's focus is not on this data, but on getting the refactoring of this piece of data code.

The previous Code

Previously used by the ADO directly read the dataset, and then to data processing, the main trouble is that you also need to manually write a DataTable to model the process, but also to deal with the relationship, more cumbersome, and need to know the fields. (Of course, dapper also needs to correspond). First look at the previous code, in short, this code is a very old form.

 Privatebaselistresult Tobaselistresult (DataSet ds) {if(ds. Tables.count >0)            {                if(ds. tables[0]. Rows.Count = =0) {                    return NewBaselistresult (); }                //information for the current user                varRowmine = ds. tables[0]. rows[0]; //User group Information                varRowfrienddetails = ds. tables[2]. Rows.cast<datarow> (). Select (x =Newgroupuserentity {ID= x["UID"]. ToInt (), Avatar= x["Avatar"]. ToString (), GroupID= x["GID"]. ToInt (), Remarkname= x["Remarkname"]. ToString (), username= x["Nickname"]. ToString (), sign= x[" Sign"]. ToString (),//The field before status is empty, and now we add his online status, the Isonline method receives a userid parameter, reads from the Redis cache whether the user is online and returnsStatus = LayIMCache.Instance.IsOnline (x["UID"]. ToInt ())?"Online":"Hide"                }). OrderByDescending (x= X.status);//this will be based on whether the user is online this field sort, to ensure that online users are at the top of the Friends list//User group information, performing grouping                varFriend = ds. tables[1]. Rows.cast<datarow> (). Select (x =Newfriendgroupentity {ID= x["ID"]. ToInt (), GroupName= x["name"]. ToString (), online=0, List= Rowfrienddetails.where (f = f.groupid = = x["ID"].                ToInt ())}); //Group Information                varGroup = ds. tables[3]. Rows.cast<datarow> (). Select (x =Newgroupentity {ID= x["ID"]. ToInt (), GroupName= x["name"]. ToString (), Avatar= x["Avatar"]. ToString (), Groupdesc= x["Groupdesc"].                ToString ()}); //user skins, the first one that is being used by defaultlist<string> Skin = ds. tables[4]. Rows.cast<datarow> (). Select (x = x[0]. ToString ()).                ToList (); Baselistresult result=NewBaselistresult {mine=Newuserentity {ID= rowmine["ID"]. ToInt (), Avatar= rowmine["Avatar"]. ToString (), sign= rowmine[" Sign"]. ToString (), username= rowmine["Nickname"]. ToString (), Status="Online"}, Friend=Friend, group=Group, Skin=Skin}; returnresult; }            return NULL; }

Below, we use dapper to try. The refactoring process does not talk first, look at the refactoring of code processing:

   Publicbaselistresult Handle (Sqlmapper.gridreader reader) {varresult =NewBaselistresult (); //user's personal dataResult.mine = reader. Readfirst<userentity>(); //Handling friend Logic start            varFriend = reader. Read<friendgroupentity>(); varGroupusers = reader. Read<groupuserentity>(); Friend. ToList (). ForEach (f=            {                //Each group of people is assigned to each groupF.list = Groupusers?. Where (x = X.groupid = =f.id);            }); Result.friend=friend; //handling friend logical End//read the user's groupResult.group = reader. Read<groupentity>(); returnresult; }

Dapper compared to ADO, it is more refreshing, first of all, to deal with Gridreader, and then directly call the Read<t> method, directly convert the table value to model, but the model value needs to correspond. Then after the conversion, in one step of logic processing, is the corresponding user with the friend group ID corresponding to. The last one returns, so it looks a lot fresher and does not have to deal with a lot of trouble. The following is a record of my development ideas.

Code Ideas

One of the first things to solve is the problem of decoupling, one of the methods in Dapper is querymultiple , which is to return a Gridreader object and then handle it. Then this Gridreader object must be used when the connection is open, so, can not directly return and then close the object, so, the form of the interface may be used to propose the processing method, or, I just think of is using func< Sqlmapper.gridreader,tresult> Way to handle the results. My code is as follows:

  Public StaticT querymultiple<t> (stringSqlObjectParam,commandtype CommandType = CommandType.Text, imultiplehandler<t> handler=NULL)        {            using(varConnection =getconnection ()) {                using(varMulti =connection. Querymultiple (SQL, Param,commandtype:commandtype)) {if(Handler = =NULL) {                        return default(T); }                    returnhandler.                Handle (multi); }            }        }

One of the Imultiplehandler is a method, the handle method, and the parameter is Gridreader. The result of type T is then returned. So in the above, my invocation is very simple, is to pass the corresponding processing class on it.

 Public class Userbaselisthandler:imultiplehandler<baselistresult>

In fact, I just suddenly thought that it might be more convenient to use Func . No more class-inheriting interfaces are defined. This article, over, refactoring code is really interesting thing, follow-up I will be a variety of experience to summarize, if you can resonate with the reader that is the best.

Layim Project's basic Data acquisition code optimization, dapper replace ADO

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.