AutoMapper – Model/ViewModel mapping and validation

The goal of this post is to implement a base class to map and initialize view models using the domain object. This base class should make not only the mapping between the model and the view model but also the validation of the view model using the model annotations.

Each requirement will be implemented in two different base classes, the validation class will inherit from the mapping one as the domain object is needed to validate the view model. It makes sense to split the logic to keep the code cleaner and also to be able to use only the mapping functionality in case that we don’t need the validation.

Result

When this class is implemented we can implement our view models like this:

public class ItemViewModel : BaseEntityMapperViewModel<ItemViewModelItem>
{
    public int Id { getset; }
    public string Name { getset; }
}

The Model

public class Item
{
    [Key]
    public int Id { getset; }
 
    [MaxLength(200)] 
    [Index(IsUnique = true)]
    public string Name { getset; }
}

Sample of usage:

ViewModel – Model

My WebAPI controllers send and receive to the client a view model instance, when a instance needs to be updated in database it needs to be mapped to the domain first. This is because my domain services know nothing about view models:

// Update item
public void Put([FromBody]ItemViewModel updatedItem)
{
    if (!_itemsService.Update(updatedItem.MapToEntity()))
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
}

Model – ViewModel

When a WebAPI need to load a instance from database and send it to the client, it loads a domain instance that needs to be mapped to a view model:

// Read item by id
public ItemViewModel Get(int id)
{
    var item = _itemsService.Get(id);
    if (item == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    return ItemViewModel.MapFromEntity(item);
}

Implementation

Continue reading

ASP MVC – Template Overview

When a new MVC Web Application is created in Visual Studio a lot of files are added to the solution. The goal of this post is to provide a small overview of all these files, this overview should make easier to understand the MVC solution structure.

The files described here are the files created by default when you add a web project using the MVC template.

Create a a Web project:

New Web Project

Use the MVC Template:

MVC Template

This is the generated project:

MVC Template Project

ASP MVC Template Overview

Let’s start enumerating some created folders:

  • Content: CSS files with view styles. (Bootstrap)
  • Fonts: Some fonts required by the CSS files.
  • Scripts: JavaScript files. (JQuery)
  • Controllers: C# files with the code that is going to be run at the server side.

Now the rest of files and folders with some more details:

Views

This folder contains *.cshtml files. The Razor engine generates the views of our web application out of these files. Typically we will have a view or a group of views for each controller. This folder also contains a Web.config don’t confuse this one with the Web.config at the root of the solution. Razor engine is configured here.

Continue reading

Entity Framework 6 – Migrations, Advanced Topics

In previous posts I created a database using EF code-first and I enabled migrations.

Now lets try some advanced topics:

  • Downgrades & migrations to specific  versions
  • Customizing Migrations
  • Execute custom SQL with the migration
  • Get migration generated SQL
  • Auto migrate when the application start and additional actions

Downgrades & migrations to specific  versions

To migrate to an specific version run in command in Package Manager Console.

Update-Database –TargetMigration: MigrationName

Customizing Migrations

Let’s add a couple of new properties to our Model and add a migration to generate the default migration. We will add some information to our recipes:

  • A name: the name shall be unique for each recipe.
  • A complexity index: each recipe shall have a complexity index from 1 to 3, the default complexity level shall be 2.

This is our new Recipe class with a name and complexity index:

public class Recipe
{
    // Primary Key
    public int RecipeId { getset; }
 
    // EF needs the virtual attribute to enable Lazy loading 
    public virtual List<Food> Ingredients { getset; }
 
    // Recipe description
    public string Description { getset; }
 
    // Recipe name
    [Index(IsUnique = true)]
    [MaxLength(200)] 
    public string Name { getset; }
 
    // Recipe complexity
    [Range(1, 3)]
    [DefaultValue(2)]
    public int Complexity { getset; }
}

Add the default migration:

PM> Add-Migration Recipe_NameAndComplexity
Scaffolding migration ‘Recipe_NameAndComplexity’.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running ‘Add-Migration Recipe_NameAndComplexity’ again.

Continue reading

Entity Framework 6 – Enable Migrations

In a previous post I tested Entity Framework 6 Code First. In a production environment it is more than probable that we would need to make changes to our Model. E.g. We could need a new property.

Using EF and code first I would expect a way to add this property to my Entity class and somehow apply this change to my database. This is what I am going to test and share in this post.

As a start point of this post I will use the model created here: Entity Framework 6 – Code First.

We have already the entity Recipe in our model, and now we would like to add a simple new property type string, to store the recipe description.

public class Recipe
{
    // Primary Key
    public int RecipeId { getset; }
 
    // EF needs the virtual attribute to enable Lazy loading 
    public virtual List<Food> Ingredients { getset; }
 
    // New property with the description of the recipe
    public string Description { getset; }
}

If we run now the application this exception will appears:

image

Enable EF Code first migrations

  • Run the Enable-Migrations command in Package Manager Console

The output should be something similar to:

PM> Enable-Migrations
Checking if the context targets an existing database…
Detected database created with a database initializer. Scaffolded migration ‘201407242003173_InitialCreate’ corresponding to existing database. To use an automatic migration instead, delete the Migrations folder and re-run Enable-Migrations specifying the -EnableAutomaticMigrations parameter.
Code First Migrations enabled for project CodeFirstAzureTest.

The command created a “Migrations” folder in my project with two classes:

Continue reading

Entity Framework 6 – Code First

This post describes briefly how to use Entity Framework 6.1.1 to create a database out of a Model defined in code. The goal is to have a summary with all the steps needed with the minimum overhead of information. I will use a Console Application.

Pre Requisites

Install Entity Framework from Nuget.

image

By default the created App.config will create the database locally.

Define Entities

Each entity will create a Table in the database. Entities are defined with a class that must contains a primary key. This primary key must be the class name + Id or a property with the annotation [Key].

Let-s create some sample entities:

public class Food
   {
       [Key]
       // Primary Key, when the PK is the name of the class + id the annotation is not needed
       public int FoodId { getset; }
 
       public string Name { getset; }
       public DateTime ExpireDate { getset; }
       public bool StillInFridge { getset; }
 
       // Define a relationship Many to Many between Food and Recipe, an intermediate table will be created 
       public virtual List<Recipe> UsedForRecipes { getset; }
   }
 
   public class Recipe
   {
       // Primary Key
       public int RecipeId { getset; }
 
       // EF needs the virtual attribute to enable Lazy loading 
       public virtual List<Food> Ingredients { getset; }
 
   }

Continue reading