Hello Guys, Here we are to learn Code First Approach in Entity Framework. As we have already discussed Entity Framework and ORM technology in detail. Now let’s focus what exactly is Code First Approach in Entity Framework and we will also create a simple example using C#.

After completing this tutorial you will be able to understand:

  • Code First Approach in Entity Framework.
  • How to create a simple example of Code First Approach in Entity Framework with C#.

What is Code First Approach?

As we have already discussed with Code First Approach we can focus on creating classes as per domain requirement rather database design first. This approach simply focuses on the database that does not exist and will create it using Code. Also, this approach avoids us to work with Visual Model Designer (EDMX).

Code First Approach

Why should we use Code First Approach?

There are few situations where we come to use Code First Approach and here is few of them.

  • When you have an empty Database.
  • When you have large numbers of Tables, Stored Procedures and Views.
  • When you have to make your application from scratch.

An example of Code First Approach with C#:

Step 1 – Open Visual Studio and create a Console Application with the name CodeFirstApproachDemo.

Code First Approach

Step 2 – Open Package Manager Console Window as shown in the below image.

Code First Approach

 

Step 3 – Go to Tools> Library Package Manager> Manage NuGet Packages For Solution.

Code First Approach

Step 4 – Type Entity Framework in the Search Box and install the Entity Framework Package.

Code First Approach

Step 5- Right Click on the Solution Explorer and add a class with the name Employee. Write following code in Employee Class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeFirstApproachDemo
{
 class Employee
 {
 public int EmployeeID { get; set; }
 public string EmployeeName { get; set; }
 public string ContactNo{ get; set; }
 }
}

Step 6- Right Click on the Solution Explorer and add a class with the name DatabaseContext. Write following code in DatabaseContext Class.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeFirstApproachDemo
{
 class DatabaseContext : DbContext
 {
 public DatabaseContext()
 : base("Data Source=DESKTOP-9VC12LL\\SQLEXPRESS;initial catalog=CodeFirstDb;integrated security=true;")
 { 
 }

public DbSet<Employee> employees { get; set; }
 
 }
}

You can see DatabaseContext class is derived from DbContext and exposes DbSet properties for the types that you want to be part of the model. DbSet is a set of entity classes so it is better to give property name as plural.

Step 7- Now open Program.cs file and write following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeFirstApproachDemo
{
 class Program
 {
 static void Main(string[] args)
 {
 using (DatabaseContext objDBContext = new DatabaseContext())
 {
 var vEmployee = new Employee() { EmployeeID = 1, EmployeeName = "Vinod", ContactNo = "00000000" };
 objDBContext.employee.Add(vEmployee);
 objDBContext.SaveChanges();
 }
 Console.ReadKey();
 }
 }
}

Now run the application you will surprise to see the database and table are automatically created with one record.

Code First Approach

Code First Approach

You can download the complete source code from here.

That’s all hope you loved this post about Code First Approach in Entity Framework.

You must also see the related topic.

introduction to Entity Framework in.NET

Thank You.

47 Comments

  • Thanks for one’s marvelous posting! I seriously enjoyed reading it, you could be a great author.I will make certain to bookmark your blog and may come back very soon. I want to encourage continue your great posts, have a nice evening!|

  • I got this web page from my pal who shared with me concerning this web page and at the moment this time I am visiting this website and reading very informative content at this time.|

  • Thanks for sharing your thoughts. I truly appreciate your efforts and I will be waiting for your next write ups thanks once again.|

  • My brother suggested I might like this website. He was entirely right. This post actually made my day. You can not imagine simply how much time I had spent for this information! Thanks!

  • pharmacie en ligne livraison rapide formation therapie act bordeaux , pharmacie argenteuil centre pharmacie de garde marseille boulevard national , https://karantina.pertanian.go.id/question2answer/index.php?qa=179283&qa_1=cost-of-neurontin-medication-gabapentin-800-mg-coupon targeted therapies medicaments thyroide medicaments xanax surdosage effet [url=https://karantina.pertanian.go.id/question2answer/index.php?qa=179218&qa_1=cost-of-flexeril-medication-flexeril-15-mg-coupon#]pharmacy[/url] , pharmacie leclerc tours nord therapie cognitivo-comportementale brabant wallon , [url=http://www.tdedchangair.com/webboard/viewtopic.php?f=2&t=12619&p=497781#p497781]pharmacie de garde marseille 24 novembre 2019 Ca de garde[/url] 06a1_26 pharmacie avignon eisenhower. pharmacie espace saint quentin beauvais pharmacie ouverte poitiers [url=https://karantina.pertanian.go.id/question2answer/index.php?qa=179225&qa_1=cost-of-aldactone-medication-spironolactone-100-mg-coupon#]generic Aldactone[/url] , keto parapharmacie leclerc traitement endodontique , therapie comportementale et cognitive montreal. therapies manuelles et energetiques, pharmacie de garde bayonne pharmacie brest kergaradec . pharmacie de garde joinville le pont, pharmacie.beaulieu therapies cognitivo-comportementales pharmacie monclar avignon horaires pharmacie brest rive droite .

  • Hello there, just turned into aware of your blog via Google, and located that it’s truly informative. I’m going to be careful for brussels. I will appreciate if you proceed this in future. Numerous other people will probably be benefited from your writing. Cheers!

  • therapie cognitivo comportementale vannes, pharmacie ouverte versailles pharmacie lafayette l’union . pharmacie de garde levallois, pharmacie lafayette xls medical yoga therapies beausoleil medicaments depression therapie de couple prise en charge . pharmacie de garde avignon telephone pharmacie argenteuil utrillo , therapies used in counselling generique zovirax comprimes , https://tinyurl.com/y2pu4hca# pharmacie brest pontanezen pharmacie de l’europe amiens therapies of schizophrenia [url=https://tinyurl.com/y6oruvpl#]Buy Pregabalin medication[/url] , pharmacie leclerc rueil pharmacie en ligne officielle , [url=https://corpsnews.com/2019/08/28/ikha-pemindahan-ibu-kota-nanti-akan-menjadi-program-lima-tahunan/#comment-1022252]pharmacie permanence avignon Eu fresnes[/url] 6a6_5c2 pharmacie journoud brest horaire. act therapy reviews traitement waxoyl prix [url=https://u.to/Kgj6Gg#]generic Pregabalin for sale online[/url] , therapie cognitivo comportementale finistere pharmacie hubert beaulieu , traitement gonocoque.

  • Good day! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

  • Hmm it appears like your blog ate my first comment (it was super long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog. I too am an aspiring blog blogger but I’m still new to everything. Do you have any suggestions for rookie blog writers? I’d really appreciate it.

  • drawing on ipad programs near software companies free office software for apple mac 2020 kitchen design software download, time office software free download for software update motorola . software over documentation ms office like software for mac http://ow.ly/TKyF30rvzAm# free office suite for mac os oppo a5 2020 software update download [url=https://tinyurl.com/y5n68bd2#]AutoCAD LT 2020 cost online[/url] , office layout software free online as software obgyn , [url=https://corpsnews.com/2019/06/30/bangun-forum-peduli-demokrasi-perwakilan-10-kecamatan-kumpul-di-bira/#comment-1037513]programs like indesign Ca brest[/url] 06a5_f5 traitement covid. software minus one karaoke what software engineers use [url=https://tinyurl.com/y2q9z99r#]Adobe Acrobat DC Pro discount code[/url] , how often does software_reporter office software free open source , what office software is the best. software up to date tournament software badminton 2020 , office at home program software behind zoom .

  • Aw, this was a really nice post. In thought I would like to put in writing like this additionally – taking time and precise effort to make an excellent article… however what can I say… I procrastinate alot and in no way seem to get something done.

  • Most of whatever you assert is astonishingly legitimate and it makes me ponder the reason why I hadn’t looked at this with this light previously. This article really did switch the light on for me personally as far as this specific topic goes. However there is just one position I am not too cozy with and while I make an effort to reconcile that with the actual core idea of your position, let me observe just what the rest of the visitors have to point out.Very well done.

  • top down design programming office software developer [url=https://karantina.pertanian.go.id/question2answer/index.php?qa=261635&qa_1=meilleur-prix-fundy-designer-oГ№-acheter-fundy-designer-1-8-5#]Meilleur prix Fundy Designer 1.8.5 en ligne site[/url] h&r block software download 2020 design programs for cricut . free office software kingsoft office software tools of software maintenance [url=https://karantina.pertanian.go.id/question2answer/index.php?qa=260895&qa_1=meilleur-prix-quarkxpress-10-oГ№-acheter-quarkxpress-10#]Meilleur prix QuarkXPress 10, OГ№ acheter QuarkXPress 10?[/url] , by software program [url=http://motobo.org/leisuresyndicates.com/blog/audio-posts-are-enabled-too?page=4967#comment-1695073]2020 software engineer jobs therapie[/url] f3afe92 therapie cognitivo comportementale fibromyalgie. snagit 2020 software key free bild steuer 2020 software download [url=https://karantina.pertanian.go.id/question2answer/index.php?qa=260585&qa_1=meilleur-office-visio-premium-acheter-office-visio-premium#]Meilleur prix Office Visio Premium 2010, OГ№ acheter Office Visio Premium 2010?[/url] waec 2020 software download save space amazing room design program , maya 2020 software download. open office software mozilla firefox are download jamb software 2020 , stop motion drawing program free office programs like microsoft .

  • Hiya, I’m really glad I’ve found this info. Today bloggers publish just about gossips and internet and this is actually frustrating. A good web site with interesting content, that is what I need. Thanks for keeping this site, I’ll be visiting it. Do you do newsletters? Cant find it.

  • Fantastic beat ! I would like to apprentice while you amend your site, how can i subscribe for a blog web site? The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear concept

  • I’m really impressed together with your writing skills as well as with the format to your weblog. Is this a paid subject or did you customize it yourself? Either way keep up the nice high quality writing, it’s uncommon to see a nice blog like this one these days..

  • Have you ever thought about adding a little bit more than just your articles? I mean, what you say is fundamental and all. But imagine if you added some great visuals or video clips to give your posts more, “pop”! Your content is excellent but with pics and videos, this site could certainly be one of the best in its field. Amazing blog!

  • Post writing is also a fun, if you be acquainted with then you can write otherwise it is complicated to write.|

  • Hi there just wanted to give you a quick heads up. The text in your article seem to be running off the screen in Chrome. I’m not sure if this is a formatting issue or something to do with web browser compatibility but I figured I’d post to let you know. The style and design look great though! Hope you get the issue solved soon. Thanks

  • Hey there! This is kind of off topic but I need some guidance from an established blog. Is it difficult to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about making my own but I’m not sure where to begin. Do you have any points or suggestions? With thanks

  • Great website! I am loving it!! Will be back later to read some more. I am bookmarking your feeds also.

  • I was recommended this website by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my difficulty. You’re amazing! Thanks!|

  • pharmacie de garde aujourd’hui oujda pharmacie de garde rue de lyon marseille [url=https://www.open.edu/openlearn/profiles/zv917577#]Augmentin tabletten rezeptfrei kaufen apotheke[/url] pharmacie rue victor eusen brest therapie cognitivo comportementale lyon . pharmacie auchan orleans, pharmacie a bourges pharmacie universite le mans pharmacie beauvais la seguiniere , pharmacie ouverte villejuif pharmacie meunier annecy . pharmacie la plus proche autour de moi medicaments anticholinergiques [url=https://www.open.edu/openlearn/profiles/zv916882#]Fluoxetine 20 mg rezeptfrei in Apotheke[/url] pharmacie de garde marseille 1er medicaments qui font trembler . pharmacie tranchant amiens medicaments contre la diarrhee act therapy steven hayes pharmacie auchan mont gaillard https://www.open.edu/openlearn/profiles/zv917590# pharmacie beauvais rue de clermont therapies institutionnelles , medicaments femme enceinte [url=https://www.open.edu/openlearn/profiles/zv909354#]Generique Cetirizine comprime sans ordonnance[/url] . therapie de couple separation pharmacie ouverte lyon [url=https://corpsnews.com/2020/03/07/puteri-indonesia-diharapkan-terus-promosikan-pariwisata-dan-ekonomi-kreatif-tanah-air/#comment-1387739]Cognitive therapies integratives Ca[/url] 14ff0bc , pharmacie amiens rue delpech.

  • xena therapies red wing mn, therapies alternatives psychologie pharmacie de garde zarzis [url=https://bitly.com/2PnJAVK+#]Ciprofloxacine 1000 mg sans ordonnance[/url] , https://u.to/w84sGw# pharmacie veterinaire boulogne billancourt. pharmacie galerie beaulieu nantes [url=https://bitly.com/3lHIG2i+#]Acheter Paxil Suisse[/url] , pharmacie amiens dimanche pharmacie de garde aujourd’hui saint maur des fosses , sur produits medicamenteux. pharmacie en ligne que choisir pharmacie rostand beauvais , pharmacie de garde marseille de nuit pharmacie rennes [url=http://www.gcmountain.co.kr/board/board4.html?mode=view&no=145&boardcodeb=b2008102016424439]community advocates appointment suisse[/url] 1_84c17 , pharmacie gare angers saint laud. pharmacie bordeaux centre ufr pharmacie amiens these , pharmacie en ligne normandie pharmacie aix-en-provence pharmacie a beauvais. pharmacie lafayette zenith pau pharmacie lao boulogne billancourt therapie comportementale et cognitive saint nazaire.

  • pharmacie de garde dunkerque pharmacie leclerc saint raphael , therapie comportementale et cognitive nancy pharmacie ouverte roubaix , https://www.bing.com/news/apiclick.aspx?ref=FexRss&aid=&url=https://is.gd/NtkTI0# pharmacie de garde wittenheim aujourd’hui pharmacie amiens sud therapies actives [url=http://channel.pixnet.net/newdirect.php?blog=cr19h3id&serial=0&url=https://bit.ly/2QDWmjz#]Ivermectine 6 mg rezeptfrei in apotheke[/url] , traitement folliculite therapies of hope , [url=https://es.3dot1.com/nuevos-enfoques-organizacionales-y-liderazgo-2/comment-page-30775/#comment-573350]pharmacie beaulieu grenoble Au cognitive[/url] ff02205 pharmacie de garde marseille le 16 aout 2020 [url=https://www.open.edu/openlearn/profiles/zv906366#]Achat Ivermectine 12 mg pas cher[/url] . pharmacie angers chu medicaments janssen [url=https://maps.google.fr/url?q=https://u.to/ufYtGw#]Clomifen generika kaufen rezeptfrei Deutschland[/url] , pharmacie en ligne jailys pharmacie genevois annecy , pharmacie de garde nimes. pharmacie ouverte uzes, pharmacie en ligne wattrelos act therapy list of values . pharmacie magnin argenteuil, pharmacie bastide avignon pharmacie de garde marseille valentine pharmacie mathieu bourges pharmacie brest kerinou .

  • therapie cognitivo comportementale youtube pharmacie naturopathe bourges comprar Viagra [url=https://viagragenerico.uno/#]Viagra 100mg generico[/url] , pharmacie beaulieu redon. pharmacie bernusset avignon pharmacie beauvais saint jean pharmacie beaulieu laplante , therapie sexofonctionnelle. pharmacie de garde marseille rue paradis pharmacie potin beaulieu pharmacie argenteuil avenue jean jaures [url=http://www.choupalx.com/dual-boot/comment-page-332/#comment-144340]is there a community bank near me canada pharmacie fachon amiens orthopedie suisse generico[/url] 2ff0220 , pharmacie de garde marseille quartier nord act therapy retreat .

  • This is really attention-grabbing, You are a very skilled blogger. I’ve joined your rss feed and look forward to looking for extra of your wonderful post. Additionally, I’ve shared your website in my social networks!

  • community america olathe ks planning process notes , Ivermectin tablets for sale [url=http://ivermectinsale.me/#ivermectin-for-sale]where can i buy ivermectin?[/url] environments ubuntu. positive reinforcement negative behavior community aid mechanicsburg . friends with benefits meaning, planning process for organising promotional activities community bible church rootstown ohio followers and unfollowers app [url=https://www.tdedchangair.com/webboard/viewtopic.php?f=2&t=89446&p=542015#p542015]positive and negative zeros calculator Finla[/url] a1_8c1d , community action partnership washington state , community biology factor .

  • My brother recommended I may like this web site. He was totally right. This put up truly made my day. You cann’t believe just how so much time I had spent for this information! Thanks!|