从数据库获取数据的ASP.NET查询

klsxnrf1  于 2022-12-15  发布在  .NET
关注(0)|答案(1)|浏览(138)

在我的ASP.NETMVC应用程序中,在注册表单中,我想用当前数据库表检查用户输入的值,如果记录匹配,就获取Id。
在这里,从用户端,我得到他们的email addresssurnamedate of birth
然后,在控制器中,我尝试匹配上述详细信息中的任何记录,以获得现有的记录ID。
问题是,运行此查询需要花费更多时间,并返回timeout
有没有更有效地搜索记录的方法?
这是我的控制器代码

public JsonResult SignUpCustomer(string emailAddress, string password, string surName, string name, DateTime dateOfBirth, string timeZone)
{

  int customerId = 0;

  try

  {
    customerId = db.Customer.AsEnumerable().Where(x => x.Sur_Name.ToLower().Contains(surName.ToLower()) && x.Date_of_birth.Date == dateOfBirth.Date && x.Email_Primary.ToLower() == emailAddress.ToLower()).Select(x => x.Id).FirstOrDefault();

    if (customerId == 0) {
      customerId = db.Customer.AsEnumerable().Where(x => x.Email_Primary.ToLower() == emailAddress.ToLower() && x.Date_of_birth.Date == dateOfBirth.Date).Select(x => x.Id).FirstOrDefault();

      if (customerId == 0) {
        customerId = db.Customer.AsEnumerable().Where(x => x.Sur_Name.ToLower().Contains(surName.ToLower()) && x.Date_of_birth.Date == dateOfBirth.Date).Select(x => x.Id).FirstOrDefault();

      }
    }

    if (customerId != 0) {
      UserAccounts accounts = new UserAccounts();
      accounts.Email_Address = emailAddress;
      accounts.Surname = surName;
      accounts.Name = name;
      accounts.Password = Crypto.Hash(password);
      accounts.Status = true;
      accounts.Created_Date = DateTime.UtcNow.AddMinutes(int.Parse(timeZone));
      accounts.Customer_Id = customerId;
      dbs.UserAccounts.Add(accounts);
      dbs.SaveChanges();

    } else {
      UserAccounts accounts = new UserAccounts();
      accounts.Email_Address = emailAddress;
      accounts.Surname = surName;
      accounts.Name = name;
      accounts.Password = Crypto.Hash(password);;
      accounts.Status = true;
      accounts.Created_Date = DateTime.UtcNow.AddMinutes(int.Parse(timeZone));
      accounts.Customer_Id = customerId;
      dbs.UserAccounts.Add(accounts);
      dbs.SaveChanges();
    }

    return Json(new {
      Success = true,

    }, JsonRequestBehavior.AllowGet);

  } catch (Exception ex) {

    throw;
  }

}
gudnpqoy

gudnpqoy1#

您可以将Linq查询清除为如下形式:

var loweredName=surName.ToLower();
var loweredEmailAddress=surName.ToLower();
var dateOfBirthDateDatePart=dateOfBirth.Date;
customerID = db.Customer.FirstOrDefault(
                 x => x.Sur_Name.ToLower().Contains(loweredName)
                   && x.Date_of_birth.Year== dateOfBirthDateDatePart.Year
                   && x.Date_of_birth.Month == dateOfBirthDateDatePart.Month 
                   && x.Date_of_birth.Day == dateOfBirthDateDatePart.Day 
                   && x.Email_Primary.ToLower() == loweredEmailAddress)?.Id;

也更改其他选择。
根据您使用的efCore的Ef版本,日期比较选项完全不同。要选择最佳方式,请检查here

相关问题