Defining an Unique Key for a property of a class in Entity Framework CodeFirst Approach

Introduction

This article explain how to Add an Unique Key for a column in a model in Enity Framework code first approch with the help of Data Annotations.

Approach

Lets say you want add Unique Key constraint for a following class string data type First_Name Property

    // Sample Class
    public class Sample
    {

            public int Id { get; set; }

            public string First_Name { get; set; }

            public string Last_Name { get; set; }
    }

Then You need to define that field with Following tags

  1.  Unique key constraint –   [Index(“IX_AnyName”, 1, IsUnique = true)]
  2.  Length of the Column – (Mandatory if this is String data type ) – [StringLength(Length in Int)]

So After above changes Code will look like this

 

   // Sample Class
    public class Sample
    {

            public int Id { get; set; }

            [Index("IX_FirstNameUniqueKey", 1, IsUnique = true)]
            [StringLength(50)]
            public string First_Name { get; set; }

            public string Last_Name { get; set; }
    }

So After above changes You will notice compile time errors in code

to avoid those we have to import following namespaces

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

After above changes you will notice another error remaining , like below

That because actually Index Attribute is in the System.ComponentModel.DataAnnotations.Schemanamespace that it was in the System.ComponentMode.DataAnnotations assembly – it’s actually in theEntityFramework assembly, so you need Install Entity Framework for this project.

In this Article I explained How to Install the Entity Framework for the Project in Visual Studio

Advertisements

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