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

Usage

  • 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.

Cheers!

20 comments:

Anonymous said...

The most amazing page I have read all day =D


http://lobinsurance.info

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...

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...

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...

[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...

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 プラダ アウトレット.
Regards

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
http://www.elitecleaningsvs.com/new/link/23334
http://www.hasenchat.net/profile/candicet43
http://wiki.foradoeixo.org.br/index.php?title=User:AshleyShi
http://www.nsppf.org.uk/wikka/KeeleywdLankfordrv
http://www.everyonenews.com/blogs/79198/250959/root-critical-elements-for-parap

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?
Thanks!

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 ... クリスチャンルブタン