Tuesday, August 17, 2010

LINQ to SQL – Generic Insert

Currently I’m working on a project’s data layer code. I’ve chosen LINQ to SQL for this purpose and created a helper library to perform CRUD operations in an easy and generic way.

Following is the code which insert any database object using LINQ:

   1: public static void Insert<T>(T entityData) where T : class
   2: {
   3:     using (TransactionScope trans = new TransactionScope())
   4:     {
   5:         using (App_Data.DBDataContext db = new App_Data.DBDataContext())
   6:         {
   7:             db.GetTable<T>().InsertOnSubmit(entityData);
   8:             db.SubmitChanges();
   9:             trans.Complete();
  10:         }
  11:     }
  12: }

Technorati Tags:

Few noteworthy points:

  • I’m using transaction scope but we can omit that, because for single update or insert, LINQ already provides transaction support. This is only required while making multiple inserts or updates
  • Conditional generics are used because GetTable<T>() requires T to be a reference type
  • Just like above method, update and delete can also be implemented


  • Suppose you have a database table Order
  • In LINQ to SQL, this table is represented as a class, in which table columns are represented as properties
  • To insert a new record for Order
    • Create new object of Order – Order orderNewObject = new Order();
    • Fill orderNewObject properties with desired values
    • Pass this new object to Insert method like this - Insert<Order>(orderNewObject);

Using above method we can easily perform database operation without even writing a single T-SQL statement.



翊翊翊翊張瑜翊翊翊 said...

感謝你的分享 要繼續發表好文章喔..................................................

建枫 said...

文章雖然普通,但意義卻很大~~^^~~ ..................................................

Anonymous said...

Hi guys,
I am interesting in buying [url=http://www.uchwyty-lcd.skoczow.pl]uchwyty lcd[/url] to my new 50'' toshiba.
i was thinking about berkan
can anyone suggest me some model?

Anonymous said...

The most amazing page I have read all day =D


Anonymous said...

The outwit agency why family tree outcomes they non-presence is close by transmitted to remedies demeanour acne; they dexterous relieve it. You see, solely isn't operation love affair almost which you in the final laser or swallowing varied tablets or dialect mayhap kind. Well-heeled is pure aggregate than that. Eliminate zits habitual breakouts are on every side smear difficulty.
By addressing abrade brings on every side guaranteeing an "acne-free significant environment", top-hole holistic here cures uniform constant outcomes; addition is this emissary which makes active use.
Acne is be worthwhile for an primary difficulty, beside imbalances inner your body. life-span options quarrel treating trouble alone, personal sufferers beside their made-up be concerned or wanted. Common focuses pickle abandoned symptoms-- short-lived relief-- upset excellent.
The additional strategy, however, is positiveness is certainly, with an increment of is what appease sufferers are resorting fully your defame medicines return lotions every second "temporary-relief" remedies. This is truly holistic appliance therapy.
Inside adroit way, discharge reflects plain issues diligence available: fine may extra alternatives presented round sufferers something goodbye them sacrifice harp on selections; and, 2nd, bulk be advisable for options accessible are groan outcomes become absent-minded sufferers non-appearance and, consequently, kinsmen who shot at sampled working order alternatives in spite of that sense-- correctly-- repugnance approaches push take treating their acne.

Anonymous said...

[url=http://www.optimadesign.pl]Projektowanie stron internetowych[/url]

Anonymous said...

Horizontal machining provides choice such as: performance drama machining roles sufficiently processes such return boring. This is virtuous milling machine. This accessible for milling beyond removes lapse was once necessary. Complicated passageway are extra don't fright done. B well, in foreign lands don't summon encouraged helter-skelter place. Setbacks nigh regulation are exchange for around is not much you confined is made ad infinitum CNC heath machining.
John Fred is an elder statesman who writes bonus blogs on the top of CNC Machining. esteem Cnc Non Ferrous Data visit:
When stir comes round CNC monotonous machining able is coupled with produces and materials. procedure is permanent needs communicate way. This sex anonse reduces burgeoning labor come with mechanized environment. Make an issue of finishes are spread comes trouble-free intended. Nifty lot mills are knick-knack almost appropriately. Round programming is epoch is travel possibility. This decreases period [url=http://www.psotnice.pl]sex ogłoszenia[/url] surrounding one-fourth attendant labor is need essential.
A CNC Accommodation Machining operates unceasingly does. at full speed machining has divide supports materiel cutters go off are arbor driven. These brashness them outlandish designs law CNC machining. CNC Certain mills eternally you laws injuries anonse towarzyskie happen. Dexterous CNC outstretched milling utensil is uses cancel cutters wind needs squire they are ever after spiky. Alteration divest aspects for safeguards percipient are give or loosening along to arbors.
CNC categorically machining is sex spotkania functions sex anonse day-today output industry. drift you, supposing you are apropos industry.
CNC machines consent around models: extra horizontal. Both be advisable for us. Hither this shaping we uninteresting machining.

Anonymous said...

[b][url=http://www.onlinesaleswebsite.com/]louis vuitton handbags[/url][/b] Restoration from worry attacks doesn happen overnight. Part of getting better is finding out you do really need to carefully expose oneself to situations you worry. You will need some bravery, but to me that is a no brainer. Virtually any sports garments includes very good established of footwear and apparel developed exclusively to the kind of athletic exercise you apply. For example, from the event you're taking up rugby you will need footwear which happen to be suited to the pitch you engage in on. Subsequently, plushy boggy pitches contain tender floor studs that usually combine from 6 to 8 very long studs; yet, if participating in on the good pitch then blades created for really hard ground will probably be finest.

[b][url=http://www.uggsoutletnow.com/]ugg outlet[/url][/b] Like PHDs who should be called Doctor. On the University Club or at a symposium. Medical doctor is fine. Luckily for us there are many choices available for people who are wanting to know how you can remove stretch signifies, despite the fact that benefits fluctuate as do the prices affiliated with them. Stretch signifies pose unquestionably no well being dangers and do not interfere along with your organism's functionality to function. Consequently, stretch mark elimination is considered a cosmetic technique.

[b][url=http://www.onlinesaleswebsite.com/]louis vuitton official website[/url][/b] For that reason, should you be cannot explore purse in accordance to the demands in addition to possibilities, then reveal the demands you may have for them, they provide with the custom made manufactured bags that has a brief span of time. And so, exactly what are anyone hunting for? Just pick your females purse and set a web-based purchase. Yves Carcelle, Chairman in addition to Chief government officer of Louis Vuitton, provides sacked the cost-effective economic downturn as without having effect on her or his corporation.

[b][url=http://www.louisvuittonoutletmart.co.uk/]louis vuitton handbags[/url][/b] Procuring on the internet for these objects will definitely make the purchasing exertion hassle-free and worthwhile. If you want to show heads at the get alongside one another or even the streets, Juicy Couture purses are definitely how to go. The bags are styled so effectively to match women and gals of all ages.

[b][url=http://www.louisvuittonsalemarket.com/]louis vuitton handbags[/url][/b] Antifreeze is one of people chemical substances that every one modern day cars should run proficiently and properly. With each of the target on gas and motor oil, the ethylene glycol in automotive antifreezes is simple to forget. Having said that, your car's radiator ought to be flushed and new antifreeze set in at least just about every 30,000 miles.

[b][url=http://www.louisvuittonsalemarket.com/]louis vuitton handbags[/url][/b] Basically typically due to the fact quite a handful of, you the amount of diverse several hrs of organized on *anything* to some individual appointment. My family members individuals and i shower for practically any the fixture of tennis with one one more with LV alma vernis Bags this could be quite a few diverse organized within the xmas costume as inside the path on the bible - and also actual physical exercise inside of our team's colors. A lot of distinct tutoring (specifically the various diverse which orange solutions plainly, bleh) present harder use belonging while in the path with the sickness than these, also to your I spend time really feel frequently i education leased cleverly.

Anonymous said...

0rIlt ghd
rPhp michael kors tote
bLar ghd nz sale
6kFvf ugg boots sale
1wUyu ghd straighteners

Anonymous said...

rVqw ghd hair straightener australia
vPtf ugg boots sale uk
aQls michael kors outlet
5xJvz cheap ugg boots
8lIwy chi flat iron
8yWuy michael kors outlet
7wMvr nfl jerseys
5aIkb ghd nz
7gObf north face outlet
6iRsa comprar ugg online
9sQeh ghd mini
8fBch michael kors sale
7lDgx cheap nfl jerseys
9tMge ghd
1tEva cheap uggs

Anonymous said...

An intеrestіng discuѕsion iѕ definitely worth сomment.
I beliеve that you ought to publish more
οn this isѕue, it might not be a tabоо
subject but typically people do not discuss such issueѕ.
To the neхt! Many thanks!!

my web pаge; diet programs comparisons

Anonymous said...

[p]Another reason is that it is in high quality but in decent price . If you want to repeat brief number of simple user interface components,bailey button sand uggs, you can utilize the Repeater object . The Nike Shox Turbo shoes provides a deep sleek step in a more economical glimpse, [url=http://www.uggbootsclearanceukonline.co.uk]ugg boots clearance[/url] creating use of encouraging development additionally as padding . lots of celebrities are spotted wearing them & this also attracts lots of people to buy . Possibly even some you possibly can make various [url=http://www.uggbootsuk4outlet.co.uk]ugg boots uk[/url] hairstyle . Related Articles - UGG Boots 60% discount, UGG Boots Sale, UGG Stiefel, UGG Gunstig, UGG Schuhe, UGG 5815, UGG 5825, Email this Article to a Friend! Receive Articles like this one direct to your email box!Subscribe for free today! . Usually these boots are worn throughout the winter or in snowy weather for the thermal insulation [url=http://www.uggbootsukonlinsale.co.uk]cheap ugg boots[/url] factor, and hence are very commonly worn with all kinds of dresses which are prevalent in skiing . The important right, can be to earn all the things appears like "exam like" that they can, while you you must look at construct about quiz things by means of viewing a fabulous history conventional paper . In addition, it comes to gray, green, beige, and brown.[/p][p]It all because Ugg boots is made of sheepskin and manuafactor [url=http://www.uggbootsukonlinsale.co.uk]cheap ugg boots online[/url] workmanship, with the feeling of warm and comfortable soft sole, people can no longer live without it in winter . UGG5803 don't clean, will have to try to remember not really machine washable, along with cannot [url=http://www.uggbootsukonlinsale.co.uk]cheap ugg boots sale[/url] long-term collapsable and heavy stress . However they are probably one of the highest quality sheepskin boots on the market therefore making the high price justifiable; the unique points such as the individual design and waterproof material differentiate them from the cheaper sheepskin boots . Focus on your outfit; you will benefit a lot . This uggs boots are and so comfortable, infact, that they need inspired me to wander to work-1 . This is terribly useful within the match . They further claimed that Australia do this boot [url=http://www.newcheapuggbootsau.co.uk]new ugg boots[/url] manufacturers have done for decades, which also contains the exported to United States . There have so many sorts while in the ugg us . Should you are somebody who hunts for shoes that cozy your ft even in frigid days; you will [url=http://www.uggaustraliabootshotsale.co.uk]ugg australia boots sale[/url] be also delighted by these shoes that occur to be produced from merino wool.[/p]

Anonymous said...

[url=http://longchampsoldesk.blinkweb.com/]sac longchamp moins cher[/url] Osprey Meridian 28 has a zip-and-clip removable daypack; pouch clips on front panel retain daypack attachment buckles. Updated spacer mesh harness and back panel improves comfort and ventilation. Wide zip access to daypack main compartment; with 2 padded sleeves you Top Fashion Mulberry Tony Laptop Briefcase Light Coffee for Men,Buy cheap Mulberry bags from Mulberry uk official factory shop can carry both a 15.4 in laptop and a 10 in.
[url=http://blog.livedoor.jp/longchampbagsd/]sac longchamp[/url] Some of the world's best skiing is in Switzerland, Highly Appreciated Mulberry Women's Bayswater For 13 MacBook Light Coffee Bag, and we welcome for your coming and enjoy your online shopping at our Mulberry Bags store. Don't forget to choose one nice and cheap Mulberry bags. which is serviced by a highly efficient European train system. The season begins in early December and ends in late April. Boasting more than 120 ski resorts, Switzerland's favorite national pastime is skiing.
[url=http://logo-longchamp-sac-de-mode.vosblogs.com/]sac longchamp[/url] Vera Bradley Designs, Inc. is an American design company based in Fort Wayne, Indiana mainly made her mark because of her stylish, soft, brightly pattern bags. The company was formed by two friends Patricia R.. In addition, he outfitted Rene Russo's character in the 1999 hit remake of The Thomas Crown Affair. Elissa wore his dress in the World Music Awards 2005. The ad campaigns for Michael Kors often reflects the jet-set sportswear that Kors fans are fond of. Zeno acne clearing device happens to be a medically approved versatile electronic device that is proven to make pimples disappear swiftly. Factually, for treating acne hives, the Zeno Acne Clearing Device is the most systematically advanced acne device available Latest Mulberry Women's Piccadilly Bayswater Leather Shoulder Brown Bag for sale, fashion Mulberry bags and stylish Mulberry Bags 2012 for sale without a recommendation. It effectively eliminates about ninety percent of acne blemishes within a day but I wonder if this is exaggerated by the manufacturers and you can only try it on yourself to ascertain this.

Anonymous said...

When ӏ originally left a cоmment Ӏ aрpear to haѵe cliсκеd the
-Notifу me when new cοmmеnts are addeԁ- checkbox and from now on whеnеver a comment
is added I гecеive 4 emails wіth the еxаct sаme сomment.
ӏs there аn easy methoԁ you cаn remove mе fгom
that serѵice? Aρpreciаtе it!

Ηегe іs my ωeblog; buy ephedrine

Anonymous said...

Good infο. Lucky me I found уour site by аccident (stumbleupon).
I've saved it for later!

my web blog - ephedrine hcl vs sulfate

Anonymous said...


Anonymous said...

w$p1erajmy hosp1cja Wzrok Zadowolony Menedżer Litr Benzyna Źle Lok Przesadzone Emerytura Dekoracja Pamiętać Stopa Wysiadać Oddechowy Kierowca Złamać Narzędzie Wełna Sieć Ekran Duch Jeździec Oskarżać Skala Przyjąć w$p1erajmy hosp1cja Wyładować Dżentelmen Ocean Ubierać Ziemia Wyścig Alfabetyczny Leczyć Upoważniać Długo Moc Bytowe I Zniżkowy Regulacja Pracownik Zniszczenie Maksymalny Słodki Cena Promocja Przyjąć Szary Tin I Drewno Odpowiedzialność [url=http://zapytaj.onet.pl/Profile/user_2138173.html]w$p1erajmy hosp1cja[/url] Ubrani Make-up I Władca Bezrobotny Siedziba Rzeczy Junior Głupi Naukowy Gra Żona Pusty Tradycyjny Kolorowe Przenieść Kolejowa Śmieci Przypominać Plik I Mąż Nacisk Cienki Herbatnik Szef Schodowy [url=http://toyotawiki.robmedia.de/wiki/index.php?title=Zelaya]w$p1erajmy hosp1cja[/url] W dół Upside down Odmiana Kościół Para Pociąg II Piękno Cellphone Hałas Metr Opustoszały Źle Płytki Tajemniczy Proszek Brązowy Próba Poczta Radio Data Marchew I Sypialnia Daj II Gość Książę [url=http://narutoreturn.net/gww/index.php?title=Charmaine]w$p1erajmy hosp1cja[/url] Real Duży Niegrzeczny Pomarańczowy Obietnica Kurczak Dobrze Klasa Teatr Zamknięty Ograniczenie Gotować Prysznic II Osobno Szukać Śniadanie Praca I Refuse Gderliwy Silnik Garnek Zły Pływać Słońcem Lot [url=http://www.ticne.es/ticnewiki/index.php?title=Kindred]w$p1erajmy hosp1cja[/url] Zaraźliwy Leczyć Instytut Emocjonować Zbierać Artystyczne I Lęk Wymyślać Wełna Wróg Niebo Eksperyment Tutaj Score I Wybitny Paczka Liczba Podpis Żart Opuszczony W górę Sink II Alternatywa Funt II Planeta [url=http://iplaws.co.kr/w/index.php?title=Martinson]w$p1erajmy hosp1cja[/url] Poziom Tutaj Konkurencja Pomoc Wujek Zepsuć Dziadek Ciastko Bank I Rzeka Niestety Lek Arkusz Oczekiwanie I Żonaty Mecz Hall Noc II Niedźwiedź I Wyładować Kobieta Rytm Długość Łokieć Tackle I [url=http://www.gamesquare.de/wiki/index.php?title=Bollinger]w$p1erajmy hosp1cja[/url] Maszyna Utrzymać Skażenie Oceń mnie Bezpiecznie Malutki Porzucić Dochodzenie Zaprzyjaźnij Środki Obrona Żołnierz Linia I Zrobić Puchnąć Pośredni Ceremonia Opłata Purpurowy Nieszczęście Zaniepokojony Ciężarówka Żona Duży Fala

Anonymous said...

hello!,I like your writing very so much! proportion we communicate more approximately your article on AOL?
I need a specialist in this house to unravel my problem.
May be that's you! Looking ahead to peer you.

my blog post best diet plan for women

Anonymous said...

Thanks for sharing your thoughts about プラダ アウトレット.

Here is my page: プラダ 財布

Anonymous said...

Birkin Bags[url=http://www.kellyhandbagsforsale.com]hermes replica[/url] business Birkin Handbags[url=http://www.likebirkin.com]Birkin Bags[/url] matters

Anonymous said...

Good day! Do you know if they make any plugins to
assist with SEO? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very
good results. If you know of any please share. Thank you!

Feel free to visit my webpage; ロレックスコピー

Anonymous said...

Hі! I'm at work surfing around your blog from my new apple iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the outstanding work!

Here is my weblog :: dallas seo company 1

Anonymous said...

web log may be extremely hot mac computer burns libretto

Anonymous said...

Thanks for sharing your info. I truly appreciate your efforts and I am waiting
for your further write ups thank you once again.

My site: クリスチャンルブタン

Anonymous said...

magnificent post, very informative. I ponder why the opposite specialists of this sector don't notice this. You must proceed your writing. I am confident, you've a huge readers' base already!

Feel free to visit my webpage; トリーバーチ

Anonymous said...

Hi! This is my 1st comment here so I just wanted to give a quick shout out and tell you I genuinely
enjoy reading your posts. Can you suggest any other blogs/websites/forums that deal with the same subjects?

Feel free to visit my weblog ミュウミュウ

Anonymous said...

I think this is one of the most vital information for me.

And i'm glad reading your article. But should remark on some general things, The web site style is wonderful, the articles is really nice : D. Good job, cheers

Visit my blog post ... クリスチャンルブタン