简体   繁体   English

如何使字段唯一ASP.NET MVC5

[英]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 { 这是(IdentityUser的)ApplicationUser的字段,这就是我所做的:名称空间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?) 找不到类型或名称空间名称“索引”(您是否缺少using指令或程序集引用?)
The type or namespace name 'IndexAttribute' could not be found (are you missing a using directive or an assembly reference?) 找不到类型或名称空间名称“ IndexAttribute”(是否缺少using指令或程序集引用?)

How can I make that field unique? 我如何才能使该领域独一无二? Or can you tell me how IdentityUser's UserName field is unique? 还是可以告诉我IdentityUser的UserName字段如何唯一? Thanks. 谢谢。

Add this: 添加:

using System.ComponentModel.DataAnnotations.Schema;

If that doesn't work, check if you have a reference to EntityFramework.dll. 如果那不起作用,请检查您是否对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? 看起来您缺少文件顶部的名称空间,还是对EntityFramework.dll的项目引用? Try putting your cursor inside the word 'Index', then hit ctrl-. 尝试将光标放在“索引”一词中,然后按Ctrl-。 -- you should see a popup menu offering something like 'resolve reference' or 'add using for using System.ComponentModel.DataAnnotations.Schema;' -您应该会看到一个弹出菜单,其中包含“解析参考”或“添加使用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. 举例来说,如果您有一个引用.net 4.5程序集的.n​​et 4.0项目,则有时会出错。 You'll need to upgrade the project to a more recent version of the framework. 您需要将项目升级到该框架的最新版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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