You are here: Platform Specific Issues > Web Environment > ASP.NET MVC Example

ASP.NET MVC Example

This example is a tiny CRUD application which shows how to use db4o in ASP.NET MVC 2.0. Download the code here. This example requires Visual Studio 2008 or new and ASP.NET MVC 2.0 installed. Unzip the project. Add the db4o-assemblies to the Lib-folder. Then open the project and run it. 

Managing Object Containers

This example uses the code from the request-example to create a object container for each request. On each new request a object container is opened. Then all operations are done on this container. When the request ends, the container is disposed.

Object Identification

This example uses a GUID for each object to identify it across requests. Persisted objects inherit from the IDHolder class which contains the id-field. Take a look at alternatives for ids. See "Comparison Of Different IDs"

Using db4o

You can use db4o as expected. Just use the request-container:

public ActionResult Index()
{
    IList<Pilot> allPilots = Db4oProvider.Database.Query<Pilot>();
    return View(allPilots);
}
HomeController.cs: Listing all pilots on the index

Using IDs

Now the ids can be used in the views and actions to identify objects. For example in a list-view you use the ids for the action-links:

<% foreach (var pilot in Model) { %>

    <tr>
        <td>
            <%= Html.ActionLink("Edit", "Edit", new { id=pilot.ID }) %> |
            <%= Html.ActionLink("Delete", "Delete", new { id = pilot.ID })%>
        </td>
        <td>
            <%= Html.Encode(pilot.Name) %>
        </td>
        <td>
            <%= Html.Encode(pilot.Points) %>
        </td>
    </tr>

<% } %>
Index.aspx: In the view use the ids to identify the objects

Another location where the ids are used is in the actions. For example when you need to store changes. First we get a object which contains all changes. Then we copy all changes to the existing object in the database and finally store it. See "Merging Changes"

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, Pilot editedPilot)
{
    Pilot databasePilot = GetPilotById(id);
    databasePilot.Name = editedPilot.Name;
    databasePilot.Points = editedPilot.Points;
    Db4oProvider.Database.Store(databasePilot);

    return RedirectToAction("Index");
}
HomeController.cs: update the object