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.

109 Comments

  • I just want to say I am new to weblog and definitely loved this web blog. Probably I’m likely to bookmark your blog . You absolutely come with awesome articles and reviews. Thank you for revealing your web-site.

  • An additional issue is that video games are generally serious in nature with the key focus on mastering rather than fun. Although, we have an entertainment feature to keep the kids engaged, each and every game is often designed to improve a specific expertise or course, such as mathmatical or technology. Thanks for your publication.

  • An interesting discussion may be valued at comment. I’m sure that you simply write read more about this topic, it will not be a taboo subject but generally individuals are not enough to communicate on such topics. To another location. Cheers

  • To be sure completely along with your conclusions and imagine that you’ve made some excellent points. Also, I prefer customized for specific cultures of this site and also the easy navigation. I’ve bookmarked your site and may return often!

  • Hello there! This blog post could not be written much better! Looking at this post reminds me of my previous roommate! He always kept talking about this. I will forward this information to him. Fairly certain he will have a very good read. Many thanks for sharing!

  • After looking over a number of the blog articles on your blog, I truly appreciate your way of writing a blog. I book marked it to my bookmark website list and will be checking back soon. Please visit my web site as well and let me know how you feel.

  • Oh my goodness! Impressive article dude! Thank you so much, However I am experiencing issues with your RSS. I don’t understand why I can’t subscribe to it. Is there anybody getting identical RSS problems? Anyone who knows the answer can you kindly respond? Thanks.

  • An additional issue is really that video gaming has become one of the all-time largest forms of entertainment for people spanning various ages. Kids have fun with video games, and adults do, too. The XBox 360 is amongst the favorite video games systems for individuals that love to have a huge variety of games available to them, along with who like to learn live with other individuals all over the world. Thank you for sharing your ideas.

  • An interesting discussion is worth comment. I think that you should write more about this issue, it might not be a taboo matter but typically folks don’t discuss such topics. To the next! Best wishes.

  • I’m impressed, I have to admit. Rarely do I come across a blog that’s equally educative and interesting, and without a doubt, you have hit the nail on the head. The issue is an issue that not enough people are speaking intelligently about. Now i’m very happy I found this in my hunt for something regarding this.

  • MetroClick specializes in building completely interactive products like Photo Booth for rental or sale, Touch Screen Kiosks, Large Touch Screen Displays , Monitors, Digital Signages and experiences. With our own hardware production facility and in-house software development teams, we are able to achieve the highest level of customization and versatility for Photo Booths, Touch Screen Kiosks, Touch Screen Monitors and Digital Signage. Visit MetroClick in NYC at http://www.metroclick.com/ or , 121 Varick St, New York, NY 10013, +1 646-843-0888.

  • MetroClick specializes in building completely interactive products like Photo Booth for rental or sale, Touch Screen Kiosks, Large Touch Screen Displays , Monitors, Digital Signages and experiences. With our own hardware production facility and in-house software development teams, we are able to achieve the highest level of customization and versatility for Photo Booths, Touch Screen Kiosks, Touch Screen Monitors and Digital Signage. Visit MetroClick in NYC at http://www.metroclick.com/ or , 121 Varick St, New York, NY 10013, +1 646-843-0888.

  • This site was… how do I say it? Relevant!! Finally I have found something which helped me. Cheers.

  • Greetings! Very helpful advice in this particular article! It is the little changes that make the most important changes. Thanks a lot for sharing!

  • Good post. I learn something new and challenging on websites I stumbleupon on a daily basis. It will always be useful to read through articles from other writers and practice something from their sites.

  • This site definitely has all of the information and facts I wanted concerning this subject and didn’t know who to ask.

  • Hi, Neat post. There is a problem together with your web site in web explorer, might check this… IE nonetheless is the market leader and a large component of people will pass over your magnificent writing due to this problem.

  • Greetings, I do think your blog might be having internet browser compatibility problems. When I look at your site in Safari, it looks fine however when opening in Internet Explorer, it has some overlapping issues. I simply wanted to give you a quick heads up! Besides that, excellent website.

  • you have a terrific blog site right here! would certainly you like to make some welcome messages on my blog site?

  • I love reading an article that can make men and women think. Also, thank you for allowing for me to comment.

  • I’d like to thank you for the efforts you’ve put in penning this blog. I really hope to view the same high-grade blog posts from you in the future as well. In truth, your creative writing abilities has motivated me to get my very own website now 😉

  • I love reading through a post that can make men and women think. Also, thank you for allowing for me to comment.

  • Next time I read a blog, I hope that it doesn’t fail me just as much as this particular one. After all, I know it was my choice to read, but I actually believed you’d have something useful to talk about. All I hear is a bunch of complaining about something you could possibly fix if you were not too busy looking for attention.

  • I just desire to advise you that I am new to having a blog and really valued your website. Likely I am inclined to store your blog post . You simply have wonderful article information. Like it for discussing with us your own website report

  • This page truly has all of the information I needed about this subject and didn’t know who to ask.

  • Sapid Agency is a Search Engine Optimization company in New York City that provides SEO Services. Their proprietary SEO strategies help struggling websites and aspiring business owners to rank their websites higher in multiple search engines like Google , Yahoo and Bing. They provide local and gmb map ranking for businesses in NYC and many other local areas. Find more at https://www.sapidagency.com/ @ 145 E 57TH NEW YORK, NY 10022, USA, +1 971 341 5608 USA

  • MetroClick specializes in building completely interactive products like Photo Booth for rental or sale, Touch Screen Kiosks, Large Touch Screen Displays , Monitors, Digital Signages and experiences. With our own hardware production facility and in-house software development teams, we are able to achieve the highest level of customization and versatility for Photo Booths, Touch Screen Kiosks, Touch Screen Monitors and Digital Signage. Visit MetroClick in NYC at http://www.metroclick.com/ or , 121 Varick St, New York, NY 10013, +1 646-843-0888.

  • It is actually practically impossible to encounter well-educated americans on this theme, nevertheless you seem like you comprehend whatever you’re writing on! Gratitude

  • There’s certainly a lot to learn about this issue. I love all of the points you have made.|

  • I merely hope to inform you that I am new to having a blog and certainly cherished your write-up. Very possible I am prone to save your blog post . You truly have stunning article materials. Truly Appreciate it for sharing with us your current url write-up

  • Incredible! This blog looks exactly like my old one! It’s on a entirely different topic but it has pretty much the same layout and design. Superb choice of colors!|

  • Can I simply say what an alleviation to discover somebody that really recognizes what theyre speaking about online. You definitely recognize exactly how to bring a problem to light and also make it vital. More people need to read this and recognize this side of the tale. I cant think youre not more popular since you definitely have the gift.

  • Aw, this was a really wonderful blog post. In concept I would like to place in composing similar to this furthermore? requiring time and also actual effort to make a very good post? however what can I say? I postpone alot as well as by no means appear to obtain something done.

  • This is very interesting, You’re a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your fantastic post. Also, I’ve shared your web site in my social networks!|

  • Nice post. I find out something extra challenging on various blog sites day-to-day. It will certainly always be stimulating to read material from various other writers as well as practice a something from their store. I?d prefer to utilize some with the content on my blog site whether you don?t mind. Natually I?ll give you a web link on your web blog site. Thanks for sharing.

  • I am commonly to blogging and i really appreciate your material. The post has really peaks my rate of interest. I am going to bookmark your website and maintain looking for new details.

  • After research a few of the article on your internet site currently, and also I really like your way of blog writing. I bookmarked it to my bookmark website list and will certainly be inspecting back soon. Pls check out my internet site as well and also let me recognize what you assume.

  • You need to participate in a competition for one of the best blog sites on the web. I will certainly suggest this site!

  • Hey would you mind sharing which blog platform you’re using? I’m going to start my own blog in the near future but I’m having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I’m looking for something unique. P.S Apologies for being off-topic but I had to ask!|

  • There is noticeably a package to understand about this. I think you made certain great points in features additionally.

  • I just wish to reveal to you that I am new to writing and incredibly cherished your website. Probably I am likely to remember your blog post . You definitely have magnificent article information. Like it for swapping with us all of your internet webpage

  • The next time I review a blog site, I wish that it doesn’t disappoint me as high as this. I indicate, I know it was my selection to review, yet I really believed youd have something interesting to claim. All I listen to is a bunch of grumbling regarding something that you can repair if you werent too active searching for attention.

  • Good day here, just became alert to your blog site through Bing, and have found that it’s pretty interesting. I’ll appreciate if you decide to retain this.

  • My partner and I stumbled over here coming from a different web page and thought I might check things out. I like what I see so i am just following you. Look forward to looking over your web page repeatedly.|

  • I was extremely pleased to find this web-site. I wanted to thanks for your time for this fantastic read!! I most definitely appreciating every little of it as well as I have you bookmarked to take a look at brand-new things you blog post.

  • An impressive share, I just offered this onto an associate that was doing a little analysis on this. As well as he in fact purchased me breakfast due to the fact that I found it for him. smile. So let me rephrase that: Thnx for the treat! Yet yeah Thnkx for investing the moment to discuss this, I feel strongly concerning it and also enjoy finding out more on this subject. Preferably, as you end up being expertise, would certainly you mind upgrading your blog with even more information? It is extremely practical for me. Huge thumb up for this article!

  • Aw, this was a really good post. In idea I would love to put in composing such as this in addition? requiring time and real initiative to make an excellent write-up? however what can I claim? I put things off alot and also never appear to get something done.

  • You made some decent factors there. I viewed on the web for the problem and found most people will certainly support with your website.

  • I’m amazed, I must say. Seldom do I encounter a blog that’s both equally educative and amusing, and let me tell you, you’ve hit the nail on the head. The issue is something that too few people are speaking intelligently about. I am very happy I came across this during my hunt for something concerning this.

  • Wonderful blog post. I learn something extra tough on different blog sites everyday. It will certainly constantly be boosting to read web content from other writers and also exercise a little something from their shop. I?d choose to make use of some with the content on my blog site whether you don?t mind. Natually I?ll provide you a link on your web blog. Many thanks for sharing.

  • Oh my goodness! an amazing post man. Thank you However I am experiencing concern with ur rss. Don?t know why Incapable to subscribe to it. Is there any person getting the same rss issue? Any individual who understands kindly respond. Thnkx

  • Do you have a spam problem on this website; I also am a blogger, and I was wanting to know your situation; we have developed some nice methods and we are looking to exchange strategies with others, why not shoot me an e-mail if interested.|

  • Hey there, You have done a fantastic job. I’ll certainly digg it and personally suggest to my friends. I am confident they will be benefited from this website.|

  • There are absolutely a lot of details like that to consider. That is an excellent point to raise. I use the thoughts over as basic motivation however clearly there are concerns like the one you bring up where the most vital point will certainly be working in sincere good faith. I don?t know if finest techniques have emerged around things like that, yet I make sure that your task is plainly recognized as an up for grabs. Both boys as well as girls feel the effect of simply a moment?s pleasure, for the remainder of their lives.

  • Greate pieces. Keep writing such kind of info on your page. Im really impressed by your site.

  • Oh my goodness! a fantastic write-up guy. Thanks However I am experiencing issue with ur rss. Don?t know why Unable to sign up for it. Exists anyone getting similar rss problem? Anybody who knows kindly react. Thnkx

  • This is really interesting, You’re a very skilled blogger. I have joined your rss feed and look forward to seeking more of your excellent post. Also, I have shared your web site in my social networks!|

  • Aw, this was a really wonderful post. In concept I would like to put in composing similar to this additionally? taking time as well as real initiative to make a great post? but what can I say? I postpone alot and by no means seem to obtain something done.

  • Youre so amazing! I don’t suppose Ive check out anything like this before. So wonderful to discover someone with some initial thoughts on this subject. realy thanks for starting this up. this website is something that is required on the web, somebody with a little originality. helpful task for bringing something new to the net!

  • I do not know if it’s just me or if everybody else encountering problems with your website. It looks like some of the written text on your posts are running off the screen. Can someone else please provide feedback and let me know if this is happening to them as well? This may be a problem with my browser because I’ve had this happen before. Cheers|

  • Heya i’m for the primary time here. I came across this board and I find It truly helpful & it helped me out much. I am hoping to offer one thing again and help others such as you aided me.|

  • When I initially commented I clicked the -Inform me when new remarks are included- checkbox as well as now each time a comment is included I get 4 e-mails with the same remark. Exists any way you can eliminate me from that service? Many thanks!

  • Hi! Would you mind if I share your blog with my facebook group? There’s a lot of folks that I think would really enjoy your content. Please let me know. Cheers|

  • Howdy! I could have sworn I’ve been to this web site before but after going through many of the posts I realized it’s new to me. Anyways, I’m certainly delighted I came across it and I’ll be bookmarking it and checking back often!|

  • Oh my benefits! an outstanding article guy. Thank you However I am experiencing problem with ur rss. Don?t recognize why Incapable to subscribe to it. Exists anyone obtaining the same rss issue? Any person that understands kindly respond. Thnkx

  • Hey there would you mind letting me know which webhost you’re utilizing? I’ve loaded your blog in 3 completely different browsers and I must say this blog loads a lot faster then most. Can you recommend a good hosting provider at a honest price? Thanks a lot, I appreciate it!|

  • I loved as much as you’ll receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get bought an shakiness over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly very often inside case you shield this increase.|

  • Hi! I simply wish to give a significant thumbs up for the great info you have here on this blog post. I will certainly be coming back to your blog site for more soon.

  • Howdy would you mind letting me know which web host you’re using? I’ve loaded your blog in 3 different internet browsers and I must say this blog loads a lot faster then most. Can you suggest a good internet hosting provider at a fair price? Thanks a lot, I appreciate it!|

  • I found your blog site on google and inspect a few of your early messages. Continue to maintain the very good operate. I simply additional up your RSS feed to my MSN News Visitor. Looking for ahead to learning more from you in the future!?

  • After looking over a handful of the blog articles on your site, I seriously appreciate your technique of blogging. I saved it to my bookmark website list and will be checking back in the near future. Please check out my web site as well and tell me your opinion.|

  • I simply want to tell you that I am just all new to blogs and seriously loved this web site. More than likely I’m likely to bookmark your site . You actually come with tremendous well written articles. Many thanks for revealing your website page.

  • whoah this weblog is fantastic i like studying your posts. Keep up the good work! You already know, many individuals are hunting round for this information, you can help them greatly. |

  • Having read this I believed it was rather informative. I appreciate you taking the time and effort to put this short article together. I once again find myself spending a significant amount of time both reading and posting comments. But so what, it was still worthwhile!|