防止重复的电子邮件地址进入数据库

时间:2016-04-18 23:03:53

标签: c# asp.net .net asp.net-mvc entity-framework

我想防止重复的条目。如果电子邮件地址已经存在,我想显示一条消息,上面写着"电子邮件地址已存在于数据库中"

这是我在CustomerController中的Create方法:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "LastName,FirstName,EnrollmentDate,Email")] Customer customer)
{
    try
    {
        if (ModelState.IsValid)
        {
            db.Customers.Add(customer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
    catch (DataException)
    {
        ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
    }

    return View(customer);
}

如何添加支票以查看数据库中是否已存在电子邮件地址?

2 个答案:

答案 0 :(得分:2)

在保存之前,您可以检查客户是否存在给定的电子邮件。

#include <iostream>
#include <string>
#include <fstream>

using namespace std;


ofstream myfile;
    int num;

int main(){

    cout << "Please Enter a number " << endl;
    cin >> num;

        while (num > 3001){
            cout << "Your input integer should be less than 3001. Try again, or -1 to exit" << endl;
            cin >> num;
            if (num == -1){
        break;
            }
        }

    bool isPrime(num);


    //cout << "CMSC 140 CRN <your course CRN> Project 5: Prime Numbers Written by a student <YourName> Due Date : DD / MM / YYYY>" <<endl;

}

bool isprime(int a){
    myfile.open("primelist.txt");
    a = num;
    int prime;

    if (a <= 1 || (a % 2 == 0)){        // check if the number is even
        cout << " that is not a prime number" << endl;
        return false;
    }
    else if (a == 2){
        cout << "tht is a prime number" << endl;
        return true;
    }
    else{
        int divisor = 3;
        int top = a - 1;
        while (divisor <= top)
        {
            if (a % divisor == 0)
                return false;
        }
        divisor += 2;  //check the odd divisions 
        return true;
    }

    for (int i = 4; i < a; i++){
        if (i % 2 != 0 || i % 3 != 0){ 
            myfile << "2, 3, " << i << endl;
        }
    }
}

或者通过唯一约束在数据库中处理它。然后,您可以捕获并处理异常。

var customer = db.Customers.FirstOrDefault(x => x.EmailAddress == Email);

if (customer == null)
{
  // save changes
}

如果要将Unique约束应用于现有表,则应按如下方式构造代码:

USE TestDB;
GO
CREATE TABLE Users
 (
   UserID int NOT NULL  IDENTITY(1,1), 
   Name varchar(100) NOT NULL,
   Surname varchar(100) NOT NULL,
   EmailAddress varchar(100) NOT NULL,
   CONSTRAINT AK_UnqueEmail UNIQUE(EmailAddress) 
); 
GO

参考:https://lgitsmart.com/2014/10/18/sql-server-tip-preventing-duplicate-records-using-the-unique-constraint/

答案 1 :(得分:1)

你可以更新你的模型,这样你就不需要检查它是否已被使用

using System.ComponentModel.DataAnnotations.Schema;

public class Customer
{
    ..... {get; set;}
    ..... {get; set;}
    //String Length = 450 will avoid error if string is set to max
    [StringLength(450)]
    [Index(IsUnique=true)]
    public string Email{get;set;}
}

或者您可以在地图中添加此内容(如果您使用的是流利的)

  public class CustomerMap : EntityTypeConfiguration<Customer>
  {
    public CustomerMap()
    {
      // ....
      Property(x => x.Email).IsRequired().HasMaxLength(450).HasColumnAnnotation("Index", new IndexAnnotation(new[] { new IndexAttribute("Index") { IsUnique = true } }));
    }
  }