Showing posts with label Code First. Show all posts
Showing posts with label Code First. Show all posts

Wednesday, July 27, 2011

Download ASP.NET MVC3 Code First Project

Last week their have been email coming from readers asking for the source code of the ASP.NET MVC 3 Entity Framework Code First implementation. GOOD NEWS! I have finally uploaded the sample project on my github public repo. The ToyStoreMVC3 is written in VB.NET and you can now download or fork the solution in your own github account. For those of you who already have a github account, you may keep track of the projects that I am into by following me on github. 

I will be entertaining feedback on the project through email and through comments. Feel free to discuss bugs and other modifications to enhance the project. Thank you for supporting my blog and watch out for more.

Download ASP.NET MVC3 Code First Project

Last week their have been email coming from readers asking for the source code of the ASP.NET MVC 3 Entity Framework Code First implementation. GOOD NEWS! I have finally uploaded the sample project on my github public repo. The ToyStoreMVC3 is written in VB.NET and you can now download or fork the solution in your own github account. For those of you who already have a github account, you may keep track of the projects that I am into by following me on github. 

I will be entertaining feedback on the project through email and through comments. Feel free to discuss bugs and other modifications to enhance the project. Thank you for supporting my blog and watch out for more.

Saturday, July 9, 2011

Video Tutorial: ASP.NET MVC, EntityFramework Code Frist

I uploaded a video demonstration of the ToyStore project. This project uses the ASP.NET MVC 3 and Entity Framework 4.1 Code First. For more information and discussion of this video, please see my earlier post which discuss the process of creating an ASP.NET MVC 3 project. I also discussed EF Code First which allows you to generate the database based from the created model classes. In the next post I will be discussing my method of integrating Jquery and other Jquery Plug-ins to this framework. 






I hope you've learn a lot from my simple tutorials. Stay tune for more of these topics and the series of articles that I will be posting about ASP.NET MVC 3.

Video Tutorial: ASP.NET MVC, EntityFramework Code Frist

I uploaded a video demonstration of the ToyStore project. This project uses the ASP.NET MVC 3 and Entity Framework 4.1 Code First. For more information and discussion of this video, please see my earlier post which discuss the process of creating an ASP.NET MVC 3 project. I also discussed EF Code First which allows you to generate the database based from the created model classes. In the next post I will be discussing my method of integrating Jquery and other Jquery Plug-ins to this framework. 






I hope you've learn a lot from my simple tutorials. Stay tune for more of these topics and the series of articles that I will be posting about ASP.NET MVC 3.

Simple ASP.NET MVC Create, Edit and Delete Tutorial


In this post I'm going to show you how to do the Create, Edit and Delete function in ASP.NET MVC 3. The previews post thought us how to create our own ASP.NET MVC 3 project for the first time. We used Entity Framework 4.1 Code Frist to create our database from our model class named Product. Let us finish creating the CRUD (Create Read Update Delete) before we proceed on integrating Jquery to our project.




Create

Lets insert the Create Function in the Home Controller. The code snippet is given bellow.

' GET: /Home/Create

Function Create() As ActionResult
Return View()
End Function

'
' POST: /Home/Create

<HttpPost()> _
Function Create(ByVal productToCreate As Product) As ActionResult
Try
' TODO: Add insert logic here
_entities.Products.Add(productToCreate)
_entities.SaveChanges()
Return (RedirectToAction("Index"))
Catch
Return View()
End Try
End Function

Notice that their are two Create functions. The first Create function will return a view which contains the form for creating the product. The second function executes the Linq to Entity function to save the object to the database. Lets create the view for this method. 

1. Right click the first Create function and select Add View.
2. Create a strongly-typed view.
3. Select the model class "ProductDBContext."
4. Select the scaffold template "Create" and then click Add. 



This will generate a view located at Views > Home > Create.vbhtml. You can see that the scaffold method creates the fields of the form according to the model class identified in adding the view. This method shows how ASP.NET MVC 3 manage its views. Figure 1, shows the view created by the scaffold method.

Figure 1. Create Product form generated by MVC 3.

Edit
Just after the Create function in the Home controller, lets insert the Edit function.

' GET: /Home/Edit/5

Function Edit(ByVal id As Integer) As ActionResult
Dim productToEdit = (From p In _entities.Products _
Where p.Id = id _
Select p).FirstOrDefault()
Return View(productToEdit)
End Function

'
' POST: /Home/Edit/5

<HttpPost()> _
Function Edit(ByVal productToEdit As Product) As ActionResult
Try
' TODO: Add update logic here
Dim originalProduct = _entities.Products.Find(productToEdit.Id)
UpdateModel(originalProduct)
_entities.SaveChanges()
Return RedirectToAction("Index")
Catch
Return View()
End Try
End Function

The method of creating the Edit function is the same with the Create function. One function will retrieve the data and  return object to the view. The other function will receive the edited value and execute the query to update the database. To create the view we will follow the same procedure as to the create function.


1. Right click the first Edit function and select Add View.
2. Create a strongly-typed view.
3. Select the model class "ProductDBContext."
4. Select the scaffold template "Edit" and then click Add. 


The scaffold method will then again create a view located at Views > Home > Edit. The view will contain a form that will be used for editing the selected product. Let us test the view by first trying to add a product to our database. I added one product as showed in Figure 2.

Figure 2. The list view showing one product.
The list view we created in the index page is now field with one record. It also includes links to Edit, Details and Delete the record. Let us try out the Edit link. Figure 3 bellow shows how the Edit view is presented.

Figure 3.  Edit view shows the selected record.

The selected record to edit populates the form. Try to edit the record and hit save. The changes will then be updated to the database. After saving the record the page will return to the index by default. Now lets try the next function Details. Figure 4 bellow shows the details of the selected record. This is the Details view that we have created earlier in the previews post. 
Figure 4. Detail view of the selected record.

Delete

To complete the CRUD we insert the Delete function after the Edit function. The code snipped for the Delete function is shown below. 

'
' GET: /Home/Delete/5

Function Delete(ByVal id As Integer) As ActionResult
Dim productToDelete = (From p In _entities.Products _
Where p.Id = id _
Select p).FirstOrDefault()
Return View(productToDelete)
End Function

'
' POST: /Home/Delete/5

<HttpPost()> _
Function Delete(ByVal productToDelete As Product) As ActionResult
Try
' TODO: Add delete logic here
Dim originalProduct = _entities.Products.Find(productToDelete.Id)
_entities.Products.Remove(originalProduct)
_entities.SaveChanges()
_entities.SaveChanges()
Return RedirectToAction("Index")
Catch
Return View()
End Try
End Function

The last Delete function also demonstrates the same concept as to the Create and Edit function. The first function will get the selected object from the database and the second function will execute the query to delete the record from the database. Figure 5 bellow shows selected record to delete. 

Figure 5. Details of the selected file to delete.

Finally we have created our first ASP.NET MVC 3 application with basic CRUD functions. Using the scaffold type views, creating the views for this project was made easy. The last part of the this series is the integration of Jquery and other Jquery plug-ins such as JqGrid, JqPopulate and JqValidate. But before that, the next post will show the video of the ToyStore project we have made in this post. 

Simple ASP.NET MVC Create, Edit and Delete Tutorial


In this post I'm going to show you how to do the Create, Edit and Delete function in ASP.NET MVC 3. The previews post thought us how to create our own ASP.NET MVC 3 project for the first time. We used Entity Framework 4.1 Code Frist to create our database from our model class named Product. Let us finish creating the CRUD (Create Read Update Delete) before we proceed on integrating Jquery to our project.


Thursday, July 7, 2011

Create ASP.NET MVC application with EntityFramework Code Frist

Creating the MVC application

Few days ago I posted a video demo on a simple project using ASP.NET MVC 2 and Jquery. In this post I will be using MVC 3 framework to create a simple Toy Store project. Lets start!

1. In Visual Studio 2010, add a new project by selecting the File>New>Project.
2. At the left side you can see a list of installed templates. Choose the language of your choice and select web.

Figure 1. Create an ASP.NET MVC 3 web application. 

3. Select ASP.NET MVC 3 Web Application using your language of choice. This project will use VB.NET    for the code behind.
4. Name the project ToyStoreMVC3Jquery and then click OK.
5. In the New ASP.NET MVC 3 Project wizard, choose Internet Application, select Razor as your view          engine and click OK. You can also select ASP as your view engine but I would prefer to use Razor.


Congratulations! You just have created your first ASP.NET MVC 3 application. Test the application by running the code you will have the result the same as the image bellow.

Figure 2. Your first ASP.NET MVC 3 application.
In Figure 2, the application already has a template that you can work on. During the creation of the project we selected the Internet Application which provide us with this template. Some people would prefer the empty project template but to omit the cost of time consuming design I prefer to use the available template.

Figure 3. The ToyStoreMVC3Jquery Solution.

The MVC 3 frameworks provides us with a default structure such as shown in Figure 3. One thing that I can point out with this structure is the separation of concern. Each folder identifies a specific role in the application.

M - Model

The M in MVC stands for Model which contains the Domain Classes that identify our entities. Each class is called a model. Let us create a model named Product.



1. Right click on the Models folder located in the Solution Explorer.
2. In the context menu, select Add > Class.
3. Name the class "Product" and click OK.
4. Right click on the project located in the Solution Explorer.
5. In the context menu, select Add Reference.
6. Select the Browse tab and navigate to "C:\Program Files (x86)\Microsoft ADO.NET Entity Framework 4.1\Binaries". Select EntityFramework.dll and click OK.


The code for the product class is written bellow. I have identified five properties of the object product. Bellow the Product class it the ProductDBContext. This class will manage the classes and the database interaction. The Entity Framework will serve as the bridge from our classes to the database. We will use the DbSet Property "Products" to execute database query. This Entity Framework method will return set of Product object instances that we can use in our application.

Product.vb

Imports System.Data.Entity
Imports System.ComponentModel.DataAnnotations

Public Class Product
Public Property Id() As Integer

<required()>
Public Property Name() As String
<required()>
Public Property Description() As String
Public Property Price() As Double
End Class

Public Class ProductDBContext
Inherits DbContext
Public Property Products() As DbSet(Of Product)

Protected Overrides Sub OnModelCreating(ByVal modelBuilder As System.Data.Entity.DbModelBuilder)

End Sub
End Class

Question: Where is the Database? 
Their are three methods that are commonly used nowadays.

  • Database First - This approach allows you to use legacy database in your ORM application. It supposes that you already have existing database and build your entity model based on this database.
  • Model First - This approach supposes creating entity model (its conceptual part), and then generating storage, mapping, and DDL for creating a database schema, based on the storage part of the model. It was implemented in that way in Entity Framework 4.1.
  • Code First -  This method depends on the location of a database. If the database is specified in the configuration, EF will locate the database by default. If the database does not exist, the EF will create the database for you. The default database will be created in the SQL Server Express with the name derived from a strongly typed name of the context.
Sounds great! I will be using the Code First method with SQL Server Express for this project. 


C - Controller

C stands for Controller. This folder contains the logic that will handle our formula and query. In this project the controller will retrieve data from the database and pass the data to the view. In a more advanced application this is not recommended. Separation of logic is very important for complex application. Today, I am using certain pasterns to identify layers for better implementation of separation of concern. Thus, creating a loosely coupled application. 

Index and Details Method

Let us start with the Index and Details method. This is the code for the controller. 

Namespace ToyStoreMVC3Jquery
Public Class HomeController
Inherits System.Web.Mvc.Controller
Private _entities As New ProductDBContext

'
' GET: /Home

Function Index() As ActionResult

Return View(_entities.Products.ToList())
End Function

'
' GET: /Home/Details/5

Function Details(ByVal id As Integer) As ActionResult
Dim result = (From p In _entities.Products _
Where p.Id = id _
Select p).FirstOrDefault()
Return View(result)
End Function
End Class
End Namespace

V - View

Finally, V which stands for View. The view is the presentation layer. This layer is what the user see and interact with. MVC framework allows us to scaffold the view. Lets proceed to understand more about this process.  

1. To create the view for index (the default page of the web application), right click the index function and select Add View.  

2. A dialog box will appear. Check the "Create a strongly-typed view" and select the model class "ProductDBContext(ToyStoreMVC3Jquery).
3. Select the scaffold template "List". Leave the other options and click Add.


We can create the Details view by just repeating the process. This time we select "Details" for the scaffolding template. The process will then generate two files (Index.vbhtml and Details.vbhtml ). These files are located at the Views folder.

Connection String

Next we have to change the connection string to implement Code First. The connection string will provide the link to the SQL Server Express. Open the Web.config and change the <connectionStrings> with this code.


Web.config

<connectionStrings>
<add name="ProductDBContext"
connectionString="Server=.\SQLEXPRESS;Database=ToySotreDB;Trusted_Connection=true"
providerName="System.Data.SqlClient" />
</connectionStrings>

Now we are done with configuration. Lets try to run our application. The expected output is that the EF will generate a database named ToyStoreDB. This database contains a table named Product with the fields that we identified earlier in the Product class. Open your SQL Server Manager and locate ToyStoreDB such as shown in Figure 4. 


Figure 4. ToyStoreDB

In the next post I will present the Create, Edit and Delete Method. 

Create ASP.NET MVC application with EntityFramework Code Frist

Creating the MVC application

Few days ago I posted a video demo on a simple project using ASP.NET MVC 2 and Jquery. In this post I will be using MVC 3 framework to create a simple Toy Store project. Lets start!

1. In Visual Studio 2010, add a new project by selecting the File>New>Project.
2. At the left side you can see a list of installed templates. Choose the language of your choice and select web.

Figure 1. Create an ASP.NET MVC 3 web application. 

3. Select ASP.NET MVC 3 Web Application using your language of choice. This project will use VB.NET    for the code behind.
4. Name the project ToyStoreMVC3Jquery and then click OK.
5. In the New ASP.NET MVC 3 Project wizard, choose Internet Application, select Razor as your view          engine and click OK. You can also select ASP as your view engine but I would prefer to use Razor.


Wednesday, July 6, 2011

ASP.NET MVC, Jquery, EntityFramework CodeFrist: Introduction


This post is part of a series of articles regarding how to Insert, Update and Delete data in the database using LINQ to SQL. Also for this project, I will be working with ASP.NET MVC 3, Jquery and Entity Framework 4.1 Code First. Before we proceed, let me give you an overview of the things that I will use in this project. 

ASP.NET MVC 3

It is a framework for building scalable, stadards-based web applications using well-established design patterns and the power of ASP.NET and the .Net Framework. This new release can also be installed side-by-side with ASP.NET MVC 2. Some of the features of this framework are listed bellow. 


For more details about this framework you can visit the site and download the latest release of ASP.NET MVC 3.

Jquery

"Jquery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript0."  - Jquery site
Now here is a good thing. ASP.NET MVC 3 come with the Jquery library. I will show you later on how its done and what are the other Javascript libraries included with the MVC framework. If you want to include Jquery in your project manually then you can download it from the Jquery website for free.

Entity Framework 4.1

"The Entity Framework is Microsoft’s recommended data access technology for new applications. Entity Framework 4.1 brings a set of powerful productivity features, including “Code First” support, the productivity-enhancing DbContext API, and the ability to work with an existing database or have it created automatically." - msdn site
You can visit the Microsoft Developer Network Platforms home page to learn more about Entity Framework 4.1 and download to try if for your self. 

Throughout this project I will be using the recommended release of .NET 4 framework. You can download the installer and upgrade your .NET framework. I have been working with .NET 4 in recent projects and so far its working fine with me. Install the recommended framework and libraries and this tutorial should help you along the way. 

Overview

In this walkthrough you will build pieces of a Toy Store application. The walkthrough will not result in a fully functional application, but instead it will use the blog classes to demonstrate the implementation of the ASP.NET MVC 3, Jquery and EF Code First features. The series of articles will tackle the following:
  • Creating the MVC application. 
  • Define classes to represent the entities of the Toy Store products.
  • Reference the Entity Framework code first assembly.
  • Create a DbContext to manage the Blog classes and data access.
  • Build and ASP.NET MVC 3 application that can insert, update and delete Toy Store products.
  • Integrate Jquery ajax and JqGrid

The action will take place in the next post. Stay tune and watch out for the completion of this project. We will learn many things and maybe you can use this with your own project.

ASP.NET MVC, Jquery, EntityFramework CodeFrist: Introduction


This post is part of a series of articles regarding how to Insert, Update and Delete data in the database using LINQ to SQL. Also for this project, I will be working with ASP.NET MVC 3, Jquery and Entity Framework 4.1 Code First. Before we proceed, let me give you an overview of the things that I will use in this project. 

ASP.NET MVC 3

It is a framework for building scalable, stadards-based web applications using well-established design patterns and the power of ASP.NET and the .Net Framework. This new release can also be installed side-by-side with ASP.NET MVC 2. Some of the features of this framework are listed bellow. 


You might also like:

Related Posts Plugin for WordPress, Blogger...