Pages

May 19, 2011

How to Create Database First in ASP.NET MVC3/MVC 3 using Entity Framework (EntityFramework - EF 4.1/EF4.1) 4.1

If you are new in ASP.NET MVC /MVC3 or in EntityFramework (EF) you should look for some articles before read this topic. If you are a beginner or apprentice then , I suggest you to watch Scott Hanselman's MVC-101 video , it will help you to learn about new ASP.NETMVC3 from beginner to advanced (if MVC2 is already known to you ,  MVC3 will not be a new path or unknown to you , basic structure remain same as MVC2).


The reason behind I am writing this topic because I haven't found any good resource to start my project as Database First in MVC using Entity Framework 4.1 (EF 4.1). In Entity Framework 4.1 coders,database designers, model designers can do what they want first, if you like to code then code first (there are lots of examples over the internet  about - code first in EF 4.1 few of them are linked in my article), if like to create model first then do it first and so on.
In this topic, I will write less and help you via images because  it's a fast and easy way to learn. So let's begin to work.


I have created a new ASP.NET 4 MVC3 HTML5 based Internet application, attached a database first as shown in the image , I recommend you to download the source and investigate yourself.
Project First Appearence - Database DB First Approach ASP.NET 4 MVC3
BlogContent DataTable Data
Taxonomy Data
ContentType Table Data
Existing Database , table relationships schema - Database DB First approach


Creating ADO.NET ENTITY Data Model From a Existing Database - Database First Approch


Generate Entity Data Model From Existing Database - DB - Database DB First approach 

Creating ConnectionString from Exiting Database - Database First approach


Entity Data Model Edmx file view


 right click on the white surface in the entity data model of Blog Database.

DBContext Generate From Entity Data Model

Creating Repository , Model and Database Table Class from the Entity Data Model, Click on 'ok' twice
Now Build your project and then do as below.
After Creating Repository, Model and DBContext from Wizard


Controller Wizard to Create V-View, C- Controller
V-View and C- Controller has been created with Read,Write, Delete, Details View ability

Created a Link for the Blog Content Controller

Preview of the Project

Code : http://www.mediafire.com/download/4oai056o5h3enlr/WebApplication3.7z


Download the Source File:
  1. Direct Link: Blog OpenSource Project - Database First Approch - ASP.NET MVC3 HTML5 Project
  2. Mediafire Link: Blog OpenSource Project - Database First Approch - ASP.NET MVC3 HTML5 Project
Related Videos of Scott Hanselman, Steve Sanderson , download High WMV for best quality experience:
  1. Scaffolding – ASP.NET, NuGet, Entity Framework Code First and More
  2. DevDays Keynote + MVC-101 + Nuget : Depth
  3. NuGet In Depth: Empowering Open Source on the .NET Platform

Author Related Links:
SEO Labels:

DB First Approch / Database First Approch / Create Database First then model then code / First effort Database - DB ASP.NET MVC 3/ MVC3 / EntityFramework Database First / EF 4.1 / EF4.1 Database First approch / EF 4.1 Database(DB) First Approch .

45 comments:

  1. stick to writing, this is not a photoshop tut...it would have much easier.

    ReplyDelete
  2. is there any place that you had been lost...? Can I help you..?

    And sorry , I haven't use photoshop , I used windows paint that's all.

    ReplyDelete
  3. I guess photos helps in understanding more practically then writing.Loved your post.

    ReplyDelete
  4. any idea why I get a "unsupported context type" error when I try to "Add-->Controller"?

    ReplyDelete
  5. did you follow the above steps as they shown? If not then try from scratch.

    Project is also posted , please try to download the project and check what is missing.

    Best of luck.

    ReplyDelete
  6. It works for me, help me a lot... One of things maybe someone here have problem with is about the SQL2008 .mdf extensions. I have to deatached my DataBase to use it like are in the sample.
    See more information here
    http://msdn.microsoft.com/en-us/library/ms190209.aspx

    ReplyDelete
  7. photos are not visible

    ReplyDelete
  8. it is visible mate .... why don't you try with proxy server , maybe your ISP is blocking it for some reason.

    ReplyDelete
  9. Hi, I just wanted to take the time to thank you for creating this tutorial, it was most excellent and it was exactly what I needed... I had spent days searching for a database first approach.

    ReplyDelete
  10. You are welcome.
    I had the same experience when I started this and then I wrote this for everyone.

    ReplyDelete
  11. You sir are a God's angel!
    We are basing our senior project on this tutorial.
    Thanks a lot!

    ReplyDelete
  12. Thank you for appreciating my post.

    ReplyDelete
  13. awesome to the point tutorial

    ReplyDelete
  14. Well done and thanks. Didn't know that you could use text template wizzard for DBContext.

    Btw don't listen to those spoilers, the pictures way is very neat. Maybe geeks need more text.

    ReplyDelete
  15. Replies
    1. thanks man. Saved me hell lot of hour.
      Stick to pics.. as they say picture speaks a 1000 words. :)

      Delete
  16. Dear Alim Ul Karim: I'm very grateful for your work.
    I recommend to newbie users to download the source file from Mediafire, extract it and use only the Blog.mdf file. Start a new project and add the extracted Blog.mdf . The 'Server Explorer' is called 'Database Explorer' in my Visual Studio 2010 Express.

    Greetings from Mexico City
    Miguel

    ReplyDelete
  17. Hi Alim, Thanks for the post. I had an issue with adding the Controller. The Model Class wasn't updating and wasn't show on the drop down. I have done everything including build, rebuild, restart, and reinstall EF.
    Any Ideas?
    Thank you.

    ReplyDelete
    Replies
    1. Can you please upload your sample project with sqlexpress db in mediafire.com so that I can help you by any means possible. Or you can also install teamviewer and I can remotely help you. Let me know, which one is suitable for you.

      Delete
  18. Hi Alim,
    Thanks for the demo,
    I am trying to use your example from start, but I stuck on the first step.
    Basically, my SQL database is sitting on SQL server, how to get it from Server Explorer? and after it loded on Server Explorer, how to use it from my MVC application in my local? should I copy the database from server to local machine? or link it directly from local to server?
    Thanks
    Dan

    ReplyDelete
    Replies
    1. You can try from this list http://www.connectionstrings.com/sql-server-2008.
      However for usual cases it could be like below pattern:

      Server=(local)\ServerName;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;

      or

      Server=(local)\ServerName;Database=myDataBase;Trusted_Connection=True;

      or you can use the Server Explorer to get the existing connected database connection string and then use the same when you are connecting with the database from the project as shown in the images.

      Delete
  19. Hi Alim
    I am trying your screen to create EF in my MVC apps, but after screen 14, I got some errors in my Error list of Model1.Designer.cs, most of them such as:
    "The type 'Test1.Models.TBDR_239' already contains a definition for 'TR_RPT_YR'...
    I did not do any special, how come I got these errors,
    As well, I did not get the design elements as you get under blog.tt.
    I only got:
    Model1.cs
    TBDR_239.cs.
    By the way, I am using MVC3 and EF 4.1. Any ideas

    ReplyDelete
    Replies
    1. Give a screen-shot or download the project and see if it runs in your machine.

      Delete
  20. excellent

    i am facing one Problem

    i create below table [Student]
    StudentId INT
    Name [VARBINARY(50)]
    Age [INT]

    I followed steps defined in snaps
    it worked fine

    now i made below change
    Set StudentId to Auto Increment
    change Name [VARBINARY(50)] to Name [VARCHAR(50)]

    jquery validation are not working for NAME

    ReplyDelete
    Replies
    1. To make it work , you have to copy the generated class from the context.tt to regular C# plain old classes and the data annotation [StringLength(50)] or [MaxLengh(50)] above the Name field and the build the project and it will work just fine... but make sure you call query and ms-validation within the page.

      Delete
    2. I know it's a redundant work but it is best way that I found over months for database first approach.

      Delete
  21. excellent

    i am facing one Problem

    i create below table [Student]
    StudentId INT
    Name [VARBINARY(50)]
    Age [INT]

    I followed steps defined in snaps
    it worked fine

    now i made below change
    Set StudentId to Auto Increment
    change Name [VARBINARY(50)] to Name [VARCHAR(50)]

    jquery validation are not working for NAME

    ReplyDelete
    Replies
    1. You have to regenerate the models from dbContext

      Delete
  22. Alim I don't see the option of adding my DbContext when I right click on the white space to add a code generation file... what should I do to fix it ?

    ReplyDelete
    Replies
    1. Use your visual studio extension manager ( Tools-> Extension Manager) to install C# DbContext generator.

      Delete
  23. Worked like a charm. This is the only blog available for Database First approach.
    Thanks

    ReplyDelete
  24. Thank you, I really appreciated it. I will post new database first approach with new concepts soon.

    ReplyDelete
  25. Alim UI Karim

    This database is compatible with .NET, Silverlight, Windows Phone, Mono, Monodroid, and Monotouch:
    http://www.kellermansoftware.com/p-43-ninja-net-database-pro.aspx

    ReplyDelete
    Replies
    1. For your information, you can use the database but the approach would not be same.

      Delete
  26. Hi,

    I followed this whole tut. I ran my application and went into the "create new" page. I filled out all the fields and when i click the create button, i get an error in the controller in the db.SaveChanges();

    System.Data.Entity.Validation.DbEntityValidationException was unhandled by user code. Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

    There were no null values.

    ReplyDelete
    Replies
    1. Hi there,

      It means your model failed to validate one or more properties. What you should is step into the Model.IsValid and check the Model where is the error exist.

      You will certainly get it. If you get it then please let me know.

      Delete
  27. Need help with this project with the following requirements,

    3. Add a local database (preferable SQL Compact Database .sdf) to your website. The database stores Job information.
    1. Use the Repository pattern to access the database, and use the Entity Framework to model your database tables into C# classes.
    2. Create actions for the users to
    1. Search jobs by keyword
    2. add a new job
    3. update or delete a job.
    4. add a company information
    5. update or delete a company
    6. All form data need to be validated.
    3. Add ApiController to provide a light weight Restful web services that allow the user to perform the tasks lised in Item #3.2 above.
    4. Security - Authentication and Authorization

    ReplyDelete
    Replies
    1. Compact and server database works same.
      From repository pattern it is not possible to generate database. You can create model/code/database first and then make the repository later.
      You can create CRUD user actions by following the images.
      For validation I will make a video later.
      For security I already have a video http://www.youtube.com/watch?v=4TsRsgiU5tA

      Finally I am sorry I haven't mastered in WEBApi yet but its really easy , you can just google for some context.

      Delete
  28. Thanks Alim, I'm converting a desktop program with an existing database, where codefirst would have been time consuming. It is interesting to me that code first gets the most attention.

    ReplyDelete
  29. Hi, can i get the source project? seems it has been removed, plz provide,
    thnks,

    ReplyDelete