简体   繁体   中英

How to make a field unique ASP.NET MVC5

I want to make Email field unique. It's a field of ApplicationUser (of IdentityUser) That's what I did : namespace BidProject.Models {

public class ApplicationUser : IdentityUser
{
    public int UserID { get; set; }
    [Index(IsUnique = true)]
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }


}

I have these references:

using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

I get these errors for that :

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

How can I make that field unique? Or can you tell me how IdentityUser's UserName field is unique? Thanks.

Add this:

using System.ComponentModel.DataAnnotations.Schema;

If that doesn't work, check if you have a reference to EntityFramework.dll.

You should specify a name for the Index. Use the below syntax.

[Index("IX_EmailUnique", 1, IsUnique = true)]

Looks like you are missing a namespace at the top of the file, or a project reference to EntityFramework.dll? Try putting your cursor inside the word 'Index', then hit ctrl-. -- you should see a popup menu offering something like 'resolve reference' or 'add using for using System.ComponentModel.DataAnnotations.Schema;'

If you've got, say, a .net 4.0 project referencing a .net 4.5 assembly, sometimes that'll break things. You'll need to upgrade the project to a more recent version of the framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM