Monday, April 18, 2011

Create Simple MVC3 App with VWDExpress and MariaDB

(continued from phosphorescence: Prepare MVC 3 with VWDExpress and MariaDB)

Create new MVC 3 project

Launch Visual Web Development 2010 Express, and at first, set the default development web server as IIS Express. [Tools]-[Options]-[Project or Solution]-[Web projdct], turn on the checkbox.
Then, create new MVC 3 project following the wizard. In this sample, I name this project as Mvc3Training. If xunit.net is installed, you can choose test project in the wizard.


Configure MVC 3 project

Add DLLs for MySql.Data and MySql.Data.Entity to References.
Then add setting for connection string in Web.config file. I name for this connection string as Mvc3TrainingContext in conventions.
........
  <connectionStrings>
........
    <add name="Mvc3TrainingContext"
         connectionString="server=localhost;port=3306;User Id=mvc3_user;password=somepassword;Persist Security Info=True;database=mvc3_training"
         providerName="MySql.Data.MySqlClient" />

  </connectionStrings>
........

Create a model class

If there are no data context classes corresponding connection string, You must create it at first in Models directory. Create a data context class named "Mvc3TrainingContext" by VWDExpress.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace Mvc3Training.Models
{
    public class Mvc3TrainingContext : DbContext
    {
    }
}

Now let's create a model class for corresponding table. In previous post, I have created the People table, so I must name a model class as Person in convensions. Create it by VWDExpress.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Mvc3Training.Models
{
    public class Person
    {
        [Required]
        public int PersonId { get; set; }
        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }
        [Required, DataType(DataType.Date)]
        public DateTime BirthDay { get; set; }
    }
}

In here, omitting about some attributes. At last, rebuild this project.

Scaffold for Model

Right click on Controllers directory, select menu for adding a controller. Then input to the dialog like below:
  • Name the controller as PeopleController
  • Select the template type as "Controller with read/write actions and views using the Entity Framework"
  • Select the model class as Person class
  • Select the data context class as Mvc3TrainingContext class
That's Okay. Launch the debug server with F5 button and access to http://localhost:*****/People. If succeeded, you can browse, CRUD pages for People table.

(Conitinue to phosphorescence: Enable ASP.NET Web Site Administration Tool with MariaDB on MVC3)

No comments:

Post a Comment