Dotneteers.net
All for .net, .net for all!

EF Code First Cookbook — Recipe #2: Add Some Spice to the Entity Definition

In the previous post you created a single-table application that defined an Order class. Entity Framework used this class and created a database with an Orders table according to the structure of the Order class, and the application used this table through the OrderDatabaseContext class.

The name, “Code First” comes from the behavior of Entity Framework: instead of creating a database model first, or connecting to an existing database, you can immediately write code that represents your data entities.

The previous recipe’s application created an Orders table according to the following entity definition:

  1. public class Order
  2. {
  3.     public int Id { get; set; }
  4.     public string Customer { get; set; }
  5.     public DateTime OrderDate { get; set; }
  6.     public decimal Total { get; set; }
  7.     public string Status { get; set; }
  8. }

But what is the exact structure of the Orders table? Using the Server Explorer to connect to the database, you can take a look at the table structure, as shown in Figure 1.

f001

Figure 1: The structure of the Orders table

The mappings between Order class properties and Orders table fields are pretty straightforward. The Entity Framework even recognized that the Id property is to be used as the primary key, moreover, it automatically added an identity field specification to it, so the value of this field is automatically generated at the SQL Server side. The handling of Id is an example of the ‘convention over configuration’ behavior of Entity Framework. Even if you do not tell, it handles Id as the primary key of the table, because of its name.

You can also see in Figure 1 that the Customer and Status properties are mapped the nvarchar(MAX) fields, and so they can hold large (up to 2GB in size) texts represented with Unicode characters. Well, it seems that you can use more appropriate field types to create the Orders table than Entity Framework did.

Instead of nvarchar(MAX) columns, I would definitely use nvarchar(n) or varchar(n), where n is a ‘realistic’ number representing the maximum length of Customer and Status properties. I do not like that my Order entity’s name is represented in its plural form in the database, because my company’s convention say we must use the singular forms.

Well, Entity Framework Code First provide you full control over the database model to be created from your entity definitions, as you will learn from this recipe.

Recipe #2: Basic Customization of the Data Structure Mappings

With this recipe you will use your own field types for the Customer and Status fields, and instruct Entity Framework to use the singular Order name instead of Orders when creating the database table from the Order class.

Ingredients

  • The clone of the Recipe01 project you created in the previous post
  • Table attribute
  •  MaxLength attribute
  •  Column attribute

Preparations

Download the source code and open the solution within the Start folder. It contains the same sample code as in Recipe #1, but the Recipe01 namespace of the original sample is reamed to Recipe02.

How to Cook

Now, you will set up the Order class to use the ‘Order’ table name insead of ‘Orders’, and change the field type of the Customer property to nvarchar(128) and the type of Status field to varchar(5). To carry out the changes, follow these steps:

  1. Add the following using clause to the beginning of the Order.cs file:

    1. using System.ComponentModel.DataAnnotations;

    This namespace — as the term “data annotations” suggests — contains attribute types that can be used to decorate types representing entities. You are going to use a few attributes from this namespace to change field types.

  2. Add the Table attribute to the Order class and decorate the Customer and Status properties, as shown in the following code snippet:

    1. using System;
    2. using System.ComponentModel.DataAnnotations;
    3.  
    4. namespace Recipe02
    5. {
    6.     [Table("Order")]
    7.     public class Order
    8.     {
    9.         public int Id { get; set; }
    10.  
    11.         [MaxLength(128)]
    12.         public string Customer { get; set; }
    13.  
    14.         public DateTime OrderDate { get; set; }
    15.         public decimal Total { get; set; }
    16.         [MaxLength(5)]
    17.         [Column(TypeName = "varchar")]
    18.         public string Status { get; set; }
    19.     }
    20. }

Taste It

Now, everything is ready to try, so taste what you’ve cooked:

  1. Run the application with Ctrl+F5. This time the application creates a new database, Recipe02.OrderDatabaseContext. In the Server Explorer create a new data connection to access this new database (connect to the .\SQLEXPRESS server and select the Recipe02.OrderDatabaseContext database).
  2. Expand the Tables node and select the Open Table Definition command from the context menu of the Order table. Now, the original table definition (Figure 1) has been changed, as shown in Figure 2. You can also recognize that the Orders table name in Figure 1 changed to Order in Figure 2.

    f002

    Figure 2: The new definition of the Orders table

How It Works

The few attributes you’ve added to the Order class instructed the Entity Framework to initialize the database with your settings, overriding the default ones. The Table attribute attached to the Order class declares that instead of using the default table name, ‘Order’ should be used. By default, Entity Framework uses the pluralized form of the entity class name. That is why the corresponding table was named Orders in Recipe #1.

The MaxLength attribute can be attached to string properties, in order to define the maximum length they can take. In the code snipped above you’ve adorned the Customer and Status properties with this attribute.

The Column attribute can be used to set up various table column properties. By setting TypeName to ‘varchar’, you’ve declared that you’d like to see the Status property as a varchar field in the database.

There are many other attributes in the System.ComponentModel.DataAnnotations namespace, in the forthcoming recipes you will learn about them.

Going On

You rarely work with single-table databases, so it’s time to create something more complex. However, before going to this direction, it is worth to learn about a few tools that may help you managing databases and tracing what’s going behind the scenes.


Posted Jul 13 2011, 06:00 AM by inovak
Filed under:
Attachment: Recipe02.zip

Comments

David McClelland wrote re: EF Code First Cookbook — Recipe #2: Add Some Spice to the Entity Definition
on Wed, Jul 13 2011 16:49

This is a great series!  I appreciate the hands-on nature (example:  showing the new definition of the the Orders table that gets created by the Entity Framework).  It's not just "download this code and run it", it's step by step - thanks!

buy clomid no prescription wrote re: EF Code First Cookbook — Recipe #2: Add Some Spice to the Entity Definition
on Mon, Feb 25 2013 15:42

Appreciate you sharing, great blog.Thanks Again. Really Great.

Tactical Heroes Hack wrote Tactical Heroes Hack
on Thu, Nov 27 2014 2:23

EF Code First Cookbook — Recipe #2: Add Some Spice to the Entity Definition - DiveDeeper's blog - Dotneteers.net