Santosh
Santosh

Reputation: 2515

How to add Unique Key for a column in a model in EF code first

I am trying to make a column as Unique key in my model.

my code is :

public class Customer
{
    [Index("abcd",IsUnique = true)]
    public int CustomerID { get; set; }
}

and I am using following references:

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

Still i am getting

Error   103 The type or namespace name 'IndexAttribute' could not be found (are you missing a using directive or an assembly reference?)    

Am i missing anything? Iam using EF 6.1 version

Thanks in advance

Upvotes: 3

Views: 3596

Answers (4)

Masciuniria
Masciuniria

Reputation: 172

Solution: Just install the Entity Framework in each project you need to use IndexAttribute.


Step-by-step instructions:

  • Open Package Manager Console
  • Copy-paste this: Install-Package EntityFramework -Version 6.2.0 -ProjectName MyProject
  • substitute "MyProject" with your project and press enter

More infos: https://www.nuget.org/packages/EntityFramework/

Upvotes: 1

Kelum
Kelum

Reputation: 1775

  1. Right click Project Reference section

  2. Then Click Add Reference in that popup left menu select Assemblies

  3. Check System.ComponentModel.DataAnnotations dll

  4. Import following namespaces in code

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

  5. Install Entity Framework for this project

Upvotes: 2

Darryl
Darryl

Reputation: 11

You need to ensure that you've got EntityFramework referenced in the project that your model class is in - I moved the model classes out of my MVC website into a separate DLL but I assumed that because IndexAttribute is in the System.ComponentModel.DataAnnotations.Schema namespace that it was in the System.ComponentMode.DataAnnotations assembly - it's actually in the EntityFramework assembly, so you need the reference.

Thanks to Animuson for pointing this out.

Upvotes: 1

Will
Will

Reputation: 41

Rephrase my answer. (apologies if shortened URL's are now allowed)

In .net 4.5 the Index attribute only exists in the file (EntityFramework.dll)

The Dll System.ComponentModel.DataAnnotations.Schema does not contain the Index attribute

The EntityFramework.dll version 6 or later contains this attribute

Browse to the file EntityFramework.dll and add a reference the error will vanish and the code will compile.

The namespace System.ComponentModel.DataAnnotations.Schema is also part of this EntityFramework.dll

I assume its a blunder by Microsoft and may be corrected in .net 5

Upvotes: 4

Related Questions