Using Code First in Entity Framework

Introduction

Generally, entity framework is majorly used by adding an edmx file into your .Net solution and creating tables or dropping tables from existing SQL database. But in certain cases when we are working on large scale applications and having layered architecture with different layers (presentation, service, business and data access) it becomes quite difficult for the developer to make it loosely coupled.

In order to explain, let’s take a simple scenario. Let suppose you have a Web Application with following layers

  1. Web Front End ( ASP.Net MVC)
  2. Service Layer (WCF, Web Services)
  3. Business Layer (Business Managers)
  4. Data Access Layer (Entity Framework)

Web Front End use some models that are bean classes to store data and transmit them the Service layer, service layers are expecting Data Contracts to be passed as parameters and Business Layers actually processes that data and passes it to Data Access Layer to perform to and fro CRUD operations.

Problem

We can make common library project that contains single bean which can be travel from presentation layer to Services and Services to Business layer. Problem arises when we need to pass it to the entity framework. As if we are not using a code first approach we need to map that class to appropriate entity framework entity class. This will increase performance decline and also increase extra effort for developer to provide mappings for all the entities.

Resolution

When you use Code First model you really don’t need to include edmx file into your solution, and you just have to define bean classes or entity classes for each table creating or created already. This helps to place all the classes in one common library that will be referenced by all and will support loosely coupling of layers.

Steps

Steps to Create Entity Framework Code First Model

  1. Create a new Project named as CommonEntities
  2. Add a Library Package Reference of EFCodeFirst using NuGet

  3. Create a new folder named as “Entities” inside your project and define all the entities. Entities contain setter getter properties for all the columns in a table.

For e.g. here are the sample classes


public
class
DocumentColumns

{

[Key]


public
Int32 ColumnId { get; set; }


public
String ColumnName { get; set; }


public
String ColumnType { get; set; }


public
Int32 TypeSize { get; set; }


public
Boolean IsPrimary { get; set; }


public
Boolean AllowNulls { get; set; }


public
Boolean IsMeasure { get; set; }


public
Int32 DocumentId { get; set; }


public
String ColumnSheets { get; set; }

}


public
class
Document

{

[Key]


public
Int32 DocumentId { get; set; }


public
String DocumentPath { get; set; }


public
String DocumentName { get; set; }


public
String DocumentDescription { get; set; }


public
String TableName { get; set; }


public
Boolean IsActive { get; set; }


public
Boolean IsStarSchema { get; set; }


public
String DatabaseName { get; set; }


public
ICollection<DocumentColumns> DocumentColumns { get; set; }

}

Attribute [Key] denotes that particular property is a primary key.

  1. Create a custom context class named as “MyDbContext” which should be derived from System.Data.Entity.DbContext

    public
    class
    SchedulerContext : System.Data.Entity.DbContext

    {


    public
    DbSet<Document> Documents { get; set; }


    public
    DbSet<DocumentColumns> DocumentColumns { get; set; }


    protected
    override
    void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)

    {

    modelBuilder.IncludeMetadataInDatabase = false;

    }

    }

Here in the above snippet I have overridden the OnModelCreating method and set IncludeMetadataInDatabase = false, this basically not create a new database. This is normally used when you have already an existing database created and you don’t want Entity Framework to create a new database for you.

  1. Add the App.config file in your project and specify the Connectionstring as follows

<connectionStrings>

<add
name=ExcelScheduler.Database.SchedulerContext


connectionString=Data Source=.\sqlexpress;Initial Catalog=SchedulerDB;Integrated Security=True


providerName=System.Data.SqlClient />

</connectionStrings>

This is all done!

Now in order the treat any entity class as WCF data contract you just need to annotate your entity class with [DataContract] attribute and properties with [DataMember] attribute. And same goes if you want to use it with Asp.Net MVC models.

104 thoughts on “Using Code First in Entity Framework

  1. Attractive element of content. I simply stumbled upon your blog and in accession capital to say that I get actually enjoyed account your blog posts. Anyway I’ll be subscribing to your augment and even I achievement you access persistently quickly.

  2. Hey would you mind sharing which blog platform you’re using? I’m looking to start my own blog in the near future but I’m having a hard time making a decision 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 completely unique. P.S Apologies for getting off-topic but I had to ask!

  3. Have you ever considered about including a little bit more than just your articles? I mean, what you say is fundamental and all. Nevertheless think of if you added some great pictures or videos to give your posts more, “pop”! Your content is excellent but with pics and videos, this website could definitely be one of the most beneficial in its field. Wonderful blog!

  4. Thanks a bunch for sharing this with all of us you actually realize what you’re speaking approximately! Bookmarked. Kindly also seek advice from my site =). We may have a hyperlink alternate agreement among us!

  5. This is very fascinating, You’re an excessively skilled blogger. I have joined your feed and look ahead to in search of extra of your excellent post. Additionally, I have shared your website in my social networks!

  6. Thanks, I have recently been looking for info about this topic for ages and yours is the greatest I’ve found out till now. However, what in regards to the bottom line? Are you sure concerning the source?

  7. Well said. I really never thought I would accept this particular viewpoint, but yet I’m starting out to consider things through a different view. I’ve got to explore more about this since it seems to be very interesting. One thing I don’t fully understand though is how all aspects are related together.

  8. Good day very cool website!! Guy .. Excellent .. Wonderful .. I’ll bookmark your website and take the feeds alsoÖI am happy to seek out a lot of helpful information here within the post, we’d like work out more techniques in this regard, thanks for sharing.

  9. I think youve produced some actually interesting points. Not as well many people would really think about this the way you just did. Im genuinely impressed that theres so significantly about this subject thats been uncovered and you did it so properly, with so very much class. Very good one you, man! Genuinely excellent things right here.

  10. Why didnt I think about this? I hear exactly what youre saying and Im so happy that I came across your blog. You really know what youre talking about, and you made me feel like I should learn more about this. Thanks for this; Im officially a huge fan of your blog

  11. I would like to thank you for the efforts you have put in writing this blog. I am hoping the same high-grade blog post from you in the upcoming as well. Actually your creative writing abilities has encouraged me to get my own web site now. Actually the blogging is spreading its wings quickly. Your write up is a great example of it.

  12. I and my guys were found to be taking note of the nice pointers on the website and then at once came up with an awful feeling I had not expressed respect to the web blog owner for those tips. These young men had been for this reason stimulated to read through all of them and have now honestly been loving them. Thank you for getting quite kind and also for opting for these kinds of awesome subject areas most people are really desperate to discover. My very own sincere regret for not expressing gratitude to sooner.

  13. I truly enjoy reading through on this internet site , it contains fantastic posts . “Something unpredictable but in the end it’s right, I hope you have the time of your life.” by Greenday.

  14. Thanks for sharing excellent informations. Your web-site is very cool. I am impressed by the details that you have on this web site. It reveals how nicely you understand this subject. Bookmarked this web page, will come back for extra articles. You, my pal, ROCK! I found just the information I already searched all over the place and simply couldn’t come across. What an ideal web site.

  15. Great goods from you, man. I’ve understand your stuff previous to and you’re just too fantastic. I really like what you’ve acquired here, really like what you’re stating and the way in which you say it. You make it entertaining and you still care for to keep it smart. I can not wait to read far more from you. This is really a wonderful website.

  16. Great post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!

  17. Terrific work! This is the type of information that should be shared around the net. Shame on the search engines for not positioning this post higher! Come on over and visit my web site . Thanks =)

  18. Do you mind if I quote a few of your posts as long as I provide credit and sources back to your site? My blog is in the very same area of interest as yours and my visitors would definitely benefit from some of the information you provide here. Please let me know if this okay with you. Thanks!

  19. I looked for a web log rrnternet site on the web and check several of all of your first content articles. Always look after along the incredible maintain. Only further more improve your RSS feed which will a good Google Thing User. Looking for to reading through even more from you shortly!…

  20. Youre so cool! I dont suppose Ive learn something like this before. So nice to seek out anyone with some authentic thoughts on this subject. realy thank you for starting this up. this website is one thing that’s needed on the web, someone with a little bit originality. useful job for bringing one thing new to the internet!

  21. Thank you for sharing superb informations. Your site is so cool. I am impressed by the details that you’ve on this site. It reveals how nicely you understand this subject. Bookmarked this website page, will come back for more articles. You, my pal, ROCK! I found simply the information I already searched all over the place and just couldn’t come across. What an ideal site.

  22. Pretty section of content. I just stumbled upon your web site and in accession capital to assert that I get in fact enjoyed account your blog posts. Any way I’ll be subscribing to your feeds and even I achievement you access consistently rapidly.

  23. I’m extremely impressed with your writing skills and also with the layout on your blog. Is this a paid theme or did you modify it yourself? Either way keep up the excellent quality writing, it is rare to see a nice blog like this one nowadays..

  24. My brother recommended I might like this website. He was entirely right. This post actually made my day. You cann’t imagine simply how much time I had spent for this information! Thanks!

  25. Thanks for this post. I definitely agree with what you are saying. I have been talking about this subject a lot lately with my mother so hopefully this will get him to see my point of view. Fingers crossed!

  26. Hmm it appears like your site ate my first comment (it was super long) so I guess I’ll just sum it up what I had written 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 helpful hints for novice blog writers? I’d certainly appreciate it.

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

  28. Hi there, just became aware of your blog through Google, and found that it is really informative. I am going to watch out for brussels. I will be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers!

  29. Reading this article was such a blessing to me today. Thank you for sharing your insights in such an interesting manner. The information has been useful to me and I will continue to use it.

  30. I became honored to get a call from a friend when he observed the important suggestions shared on your site. Examining your blog posting is a real fantastic experience. Many thanks for thinking about readers much like me, and I would like for you the best of success for a professional in this surface area.

  31. Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your website? My website is in the very same niche as yours and my users would certainly benefit from some of the information you present here. Please let me know if this ok with you. Thanks a lot!

  32. this was a very humorous read. i enjoyed it damned much!|Thanks for this article! In any case, I had a emotionally upset viewing this article in Safari 5. Fair wanted to give rise to that to your limelight! Thanks.

  33. Pretty section of content. I just stumbled upon your web site and in accession capital to assert that I get actually enjoyed account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently fast.

Leave a reply to vancouver photo booth Cancel reply