Posted by: Cirilo Meggiolaro | 04/14/2009

Tip of the day #182 – ASP.NET MVC – Model

The Model classes are responsible for accessing and manipulating data, applying business validation rules and exposing methods that will be invoked by Controller classes.

The model classes don’t have any special feature, naming conventions and so on. You are free to access and manipulate data and create the methods you need in the way that fits better to your organization rules, database and application types. For this tip, I am going to create a class and use basic features of ADO.NET Entity Framework to access and manipulate data on the database. Some code was omitted for brevity and only the code needed to execute the operations was provided.

How to…

  • Create a database called MVCStore with two tables as shown on the diagram below:

Picture 1 - MVCStore database tables

Picture 1 - MVCStore database tables

The first table stores information about products while the second is a table that stores information about product categories.

  • Open Visual Studio 2008;
  • Create a new ASP.NET MVC Web application;
  • On the Solution Explorer window, right-click the Models folder and select Add > New Item;
  • Select ADO.NET Entity Data Model, name it mvcstore.edmx and click ok;
  • The Entity Data Model Wizard is displayed. Select Generate from database and click Next button;

Picture 2 - Entity Model Wizard Step 1

Picture 2 - Entity Model Wizard Step 1

  • On the second step, click on New Connection button. The Connection Properties dialog is shown;
  • Enter the server, database name and username and password (if needed), click on Test Connection to make sure that the connection information is valid and click OK;

Picture 3 - Entity Model Wizard Step 2

Picture 3 - Entity Model Wizard Step 2

  • Back to the wizard, click Next;
  • The next step is to select the objects we want to add to the model. If you need to change later you can. For this example, expand the Tables node and select both product and category tables and click Finish;

Picture 4 - Entity Model Wizard Step 3

Picture 4 - Entity Model Wizard Step 3

  • The edmx file is displayed. Let’s change some names to make it easier to code;

Picture 5 - The entity model with the product and category entities

Picture 5 - The entity model with the product and category entities

  • Select the product entity. On the properties window, change name to Product and EntitySet to Products;
  • Select the category entity. On the properties window, change name to Category and EntitySet to Categories;
  • Right-click the Models folder and select Add > Class;
  • Name it ProductModel and click OK;
  • On the ProductModel class we are going to wrap the CRUD (create, read, update and delete) operations and also retrieve a list of all products. The code will be similar to the following:

public class ProductModel
{
    MVCStoreEntities _context = new MVCStoreEntities();

    internal void Insert(Product product)
    {
        _context.AddToProducts(product);
        this.Save();
    }

    internal void Update(FormCollection form)
    {
        var product = this.Get(Int32.Parse(form[“id”]));

        product.name = form[“name”];
        product.description = form[“description”];
        product.items_available = Int32.Parse(form[“items_available”]);

        if (form[“active”] != “false”)
            product.active = true;
        else
            product.active = false;

        product.category = this.GetCategory(Int32.Parse(form[“category”]));

        this.Save();
    }

    internal void Save()
    {
        _context.SaveChanges();
    }

    internal void Delete(int id)
    {
        Product prod = this.Get(id);
        _context.DeleteObject(prod);
        this.Save();
    }

    internal Product Get(int id)
    {
        var product = _context.Products.First(p => p.id == id);

        if (!product.categoryReference.IsLoaded)
            product.categoryReference.Load();

        return product;
    }

    internal List<Product> GetList()
    {
        List<Product> prods = _context.Products.ToList();

        foreach (Product prod in prods)
        {
            prod.categoryReference.Load();
        }

        return prods;
    }

    internal List<Category> GetCategories()
    {
        return _context.Categories.ToList();
    }

    internal Category GetCategory(int id)
    {
        return _context.Categories.First(c => c.id == id);
    }
}

On the code above we create an instance of the MVCStoreEntities class that is the context of our data access. All methods to insert, retrieve, delete and persist changes come from this object. After that we create one simple method for each operation we need.

It’s important to say that on the Get and GetList methods the category item that is referenced by the product is loaded so it can be accessed from the Views. Keep in mind that for real scenario applications you should consider optimize these operations and retrieve only the information you really need to display such as the category description and the category id.

Tomorrow we are going to check how to work with Views.

Stay tuned!

Advertisements

Responses

  1. ADO.NET Entity Data Model is not visible

    help me

  2. Hi,

    To start coding ADO.NET Entity Framework applications, you need to install the .NET Framework 3.5 service pack 1. If you are using Visual Studio 2008, I recommend you to install the Service Pack 1 also. The links are available below:

    .NET Framework 3.5 Service Pack 1
    http://www.microsoft.com/downloads/details.aspx?familyid=AB99342F-5D1A-413D-8319-81DA479AB0D7&displaylang=en

    Visual Studio 2008 Service Pack 1
    http://www.microsoft.com/downloads/details.aspx?FamilyId=FBEE1648-7106-44A7-9649-6D9F6D58056E&displaylang=en

    Thanks for your visit!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: