Entity Framework: Code First Data Annotations

Introduction

The Entity Framework Code First approach allows us to use our POCO (domain) classes as a model and Entity Framework can use the classes to query data, change tracking, and other update functions.

Entity Framework Code First provides a set of data annotation attributes that can be applied to domain classes or the properties of domain classes.

Normally we can divide these data annotations into the following two categories.

  1. Database Schema-related Attributes
    • Table
    • Column
    • Key
    • Timestamp
    • ConcurrencyCheck
    • ForeignKey
    • InverseProperty
    • Index
    • DatabaseGenerated
    • ComplexType
    • NotMapped
  2. Validation Attributes
    • Required
    • MinLength
    • MaxLength
    • StringLength

Table Attribute

Table attributes specify the name of the table and define the schema. This means that this attribute can be used when the entity name and table name in the database are different.

[Table("Department", Schema = "dbo")]
public class DepartmentMaster
{
    // Add your class properties and methods here
}

In the preceding example, my entity name is “DepartmentMaster” and my database table name is “Department”.

Column Attribute

The same as the table attribute, this attribute specifies the name of the column and the data type of the column. This means that this attribute is very useful when the entity's property name and the table's column name are different.

The following are some important properties of the Column Attribute.

  • Order: Order in which a column appears in the table.
  • TypeName: Name the database type of the column.

Example

[Table("Employee", Schema = "dbo")]
public class Employee
{
    [Column("ID", Order = 1)]
    public int EmployeeId { get; set; }

    [Column("Name", Order = 2, TypeName = "varchar(100)")]
    public string EmployeeName { get; set; }
}

Key Attribute

Entity Framework believes that every entity has a primary key and that key is used for tracking the entities. The Key Attribute specifies the property/column that is the part of the primary key of the entity and it applies only to scalar properties.

Example

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

[Table("Department", Schema = "dbo")]
public class DepartmentMaster
{
    [Key]
    public int DepartmentId { get; set; }
}

Composite keys

An Entity Framework Code First model also supports a composite primary key (a composite primary key has more than one property).

Example

[Table("Department", Schema = "dbo")]
public class DepartmentMaster
{
    [Key]
    public int DepartmentId { get; set; }

    [Key]
    public int CompanyId { get; set; }
}

Timestamp Attribute

The Timestamp attribute specifies the byte array (byte []) property/column that has a concurrency mode of "Fixed" in the model and it should be a Timestamp column in the stored model (database).

Example

[Timestamp]
public byte[] TimeStamp { get; set; }

ConcurrencyCheck Attribute

The ConcurrencyCheck Attribute is used to specify a property/column that has a concurrency mode of “fixed” in the EDM model. This attribute can be used with scalar properties only. A fixed concurrency mode means that this property is a part of the concurrency check during save operations.

Example

[ConcurrencyCheck]
public string Name { get; set; }

ForeignKey Attribute

This attribute specifies the foreign key for the Navigation property.

Example

[Table("Employee", Schema = "dbo")]
public class Employee
{
    [Column("ID", Order = 1)]
    public int EmployeeId { get; set; }

    [Column("Name", Order = 2, TypeName = "varchar(100)")]
    public string EmployeeName { get; set; }

    [ForeignKey("DepartmentId")]
    public int DepartmentId { get; set; }

    [ForeignKey("DepartmentId")]
    public DepartmentMaster Department { get; set; }
}

InverseProperty Attribute

A relationship in the Entity Framework always has two ends, a navigation property on each side and an Entity Framework that maps them together automatically by convention. If there are multiple relationships between the two entities, Entity Framework cannot handle the relationships. This is because Entity Framework doesn't know which navigation property map with which properties on another side. For example, an Employee is bound with two departments one is the primary and the other is the secondary. In this scenario, Entity Framework does not know which navigation properties on the opposite side should be returned.

Using an InverseProperty attribute, we can specify which navigation property should be returned.

Example

[Table("Department", Schema = "dbo")]
public class DepartmentMaster
{
    [Key]
    public int DepartmentId { get; set; }

    [Required]
    public string Code { get; set; }

    [MinLength(5)]
    [MaxLength(100)]
    [Index("IX_Name_DepartmentMaster", IsClustered = false, Order = 2)]
    public string Name { get; set; }

    public ICollection<Employee> PrimaryEmployees { get; set; }
    public ICollection<Employee> SecondaryEmployees { get; set; }
}

[Table("Employee", Schema = "dbo")]
public class Employee
{
    [Column("ID", Order = 1)]
    public int EmployeeId { get; set; }

    [Column("Name", Order = 2, TypeName = "varchar(100)")]
    public string EmployeeName { get; set; }

    [InverseProperty("PrimaryEmployees")]
    public DepartmentMaster PrimaryDepartment { get; set; }

    [InverseProperty("SecondaryEmployees")]
    public DepartmentMaster SecondaryDepartment { get; set; }
}

Index Attribute

An index data annotation attribute is introduced with Entity Framework 6.1. The property of the model can be marked with an attribute and it should participate in a store index. The Index attribute allows us to create an index on one or more columns and we can specify the name of the index.

Example

[Index("IX_Name_DepartmentMaster", IsClustered = false)]
public string Name { get; set; }

DatabaseGenerated Attribute

The DatabaseGenerated attribute specifies that the property of the model will be used for either identity or Computed column of the database table so that this property will be read-only and the Entity Framework does not try to update this field into the database table. The Entity Framework will update this field from the database after the insert or update.

Example

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime DateCreated { get; set; }

Database

ComplexType Attribute

The Complex types are the non-scalar properties of an entity that enable scalar properties to be organized within the entities. A Complex type may have scalar properties or other complex type properties. Complex types do not have a key and Identity so Entity Framework cannot manage these objects apart from the parent entity. A Complex type entity can be also used for a Stored Procedure result.

Example

[ComplexType]
public class UserInfo
{
    public DateTime CreatedDate { get; set; }
    public string CreatedBy { get; set; }
}

[Table("Department", Schema = "dbo")]
public class DepartmentMaster
{
    [Key]
    public int DepartmentId { get; set; }
    // Other properties...

    public UserInfo User { get; set; }
}

NotMapped Attribute

In the Code First model approach, every property of the model is represented as a table column in the database. This is not always the case, we might require some property in a model or entity that is not present in the database table. For example, my Department entity has a property called DepartmentCodeName, this property returns a combination of code and name separated by a colon(:). This property can be created dynamically and there is no need to store it in the database. We can mark this property with NotMapped annotation. In short, if we decorate any property or class with this attribute then they should be excluded from database mapping.

Example

public class DepartmentMaster
{
    [NotMapped]
    public string DepartmentCodeName
    {
        get
        {
            return Code + ":" + Name;
        }
    }
    // Other members of DepartmentMaster
}

[NotMapped]
public class InternalClass
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Required Attribute

The Required attribute tells the Entity Framework that this property must have a value and this attribute will force the Entity Framework to ensure that this has data in it. This attribute will also participate in database creation (by marking this column as “not nullable”).

Example

[Required]
public string Code { get; set; }

Entity framework

MinLength Attribute

This attribute is used to validate a property, whether the property has a minimum length of string.

Example

[MinLength(5)]
public string Name { get; set; }

MaxLength Attribute

The maxlength attribute allows us to specify additional property validations to set the maximum length of the string. This attribute will also participate in database creation (by setting the length of the property).

Example

[MinLength(5)]
[MaxLength(100)]
public string Name { get; set; }

StringLength Attribute

StringLength is used to specify the maximum length of the string. This attribute is applied only to string-type properties. We can also specify a minimum length of characters that are allowed in the data field. This attribute will also participate in database creation (by setting the length of the property).

Example

[StringLength(100, MinimumLength = 5)]
public string Name { get; set; }

Attribute

Summary

Generally, data annotations are used for client-side and server-side validation. This article describes how data annotation can help us to configure our classes in the Code First model.


Similar Articles