如何使字段唯一 ASP.NET MVC5

How to make a field unique ASP.NET MVC5

我想让电子邮件字段唯一。这是 ApplicationUser 的一个字段(IdentityUser 的)这就是我所做的: 命名空间 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; }


}

我有这些参考资料:

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

我得到这些错误:

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?)

如何使该字段唯一?或者您能告诉我 IdentityUser 的 UserName 字段是如何唯一的吗?谢谢

您应该为索引指定一个名称。使用以下语法。

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

添加这个:

using System.ComponentModel.DataAnnotations.Schema;

如果这不起作用,请检查您是否有对 EntityFramework.dll 的引用。

您似乎缺少文件顶部的命名空间,或者缺少对 EntityFramework.dll 的项目引用?尝试将光标放在单词 'Index' 内,然后按 ctrl-。 -- 您应该会看到一个弹出菜单,提供类似 'resolve reference' 或 'add using for using System.ComponentModel.DataAnnotations.Schema;'

的内容

例如,如果您有一个引用 .net 4.5 程序集的 .net 4.0 项目,有时这会破坏某些东西。您需要将项目升级到更新版本的框架。