我需要對我的代碼的建議。我想要做的是在 ASP.NET Core 中使用 Entity Framework Core 在表中插入一行。
在插入新資料之前,我想檢查電子郵件和電話號碼是否已被使用。
我想具體回傳,例如如果回傳 = x,使用電子郵件。如果 return = y,則使用電話。
這是我的代碼
public int Insert(Employee employee)
{
var checkEmail = context.Employees.Single(e => e.Email == employee.Email);
if (checkEmail != null)
{
var checkPhone = context.Employees.Single(e => e.Phone == employee.Phone);
if (checkPhone != null)
{
context.Employees.Add(employee);
context.SaveChanges();
return 1;
}
return 2;
}
return 3;
}
我不確定我的代碼,對我的情況有什么最佳實踐建議嗎?
uj5u.com熱心網友回復:
我只是不喜歡這些表示您的檢查結果的“神奇數字”……從現在起 6 個月后,您或其他人將如何知道什么1或2意味著什么?
我建議要么至少創建一個常量類,使之更明顯這些數字的含義:
public class CheckConstants
{
public const int Successful = 1;
public const int PhoneExists = 2;
public const int EmailExists = 3;
}
然后在您的代碼中使用這些常量:
public int Insert(Employee employee)
{
var checkEmail = context.Employees.Single(e => e.Email == employee.Email);
if (checkEmail != null)
{
var checkPhone = context.Employees.Single(e => e.Phone == employee.Phone);
if (checkPhone != null)
{
context.Employees.Add(employee);
context.SaveChanges();
return CheckConstants.Successful;
}
return CheckConstants.PhoneExists;
}
return CheckConstants.EmailExists;
}
以及在呼叫此方法并需要了解回傳狀態代碼的任何代碼中。
或者,您也可以將其更改為列舉(而不是int):
public enum CheckConstants
{
Successful, PhoneExists, EmailExists
}
然后int從你的方法中回傳這個列舉 - 而不是- :
public CheckConstants Insert(Employee employee)
{
var checkEmail = context.Employees.Single(e => e.Email == employee.Email);
if (checkEmail != null)
{
var checkPhone = context.Employees.Single(e => e.Phone == employee.Phone);
if (checkPhone != null)
{
context.Employees.Add(employee);
context.SaveChanges();
return CheckConstants.Successful;
}
return CheckConstants.PhoneExists;
}
return CheckConstants.EmailExists;
}
uj5u.com熱心網友回復:
將兩個資料庫檢查合并為一個查詢
使用 SingleOrDefault 實體 Single
public int Insert(Employee employee) { var checkEmail = context.Employees.Select (e=>new {e.Email , e.Phone }).SingleOrDefault(e => e.Email == employee.Email || e.Phone == employee.Phone); if (checkEmail == null) { context.Employees.Add(employee); context.SaveChanges(); return 1; } else if (checkEmail.Email == employee.Email) return 3; else return 2; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/394418.html
