c# - 验证服务 ASP.NET CORE MVC (c#) 中的重复电子邮件条目
问题描述
- 我希望我的 CRUD 页面中的 Edit 方法不允许重复的电子邮件条目。如果用户在编辑时尝试输入已经存在的电子邮件,那么用户应该会收到一条错误消息。到目前为止,我有这个。任何人都可以帮助我:)
编辑方法
public async Task<DataOperationResult> EditAsync(Guid id, string name, string email)
{
try
{
DataOperationResult result = new DataOperationResult();
var originalUser = _context.InterestedParties.Find(id);
// Found the user, update it.
originalUser.Name = name;
//TODO: validate - duplicate email
if (originalUser.Name == name)
{
return new DataOperationResult
{
Success = false,
Message = $"Could not locate a user with this ID {id}"
};
}
_context.Update(originalUser);
await _context.SaveChangesAsync();
result.Success = true;
result.Message = "User updated.";
_logger.LogTrace($"User {id} has been updated.");
return result;
}
catch (Exception ex)
{
throw new Exception($"Failed to update user.", ex);
}
}
创建方法
- 我希望我的 crud 页面中的 Create 方法不允许重复的电子邮件条目。如果用户在创建时尝试输入已经存在的电子邮件,那么用户应该会收到一条错误消息。到目前为止,我有这个。
public async Task CreateInterestedPartyAsync(string name, string email)
{
DataOperationResult result = new DataOperationResult();
var dbInterestedParty = _context.InterestedParties.ToList();
if (dbInterestedParty.Any(dbInterestedParty => dbInterestedParty.Email == email))
{
result.Success = false;
result.Message = "Interested Party already exists in database";
}
else
{
_context.Add(new InterestedParty()
{
Name = name,
Email = email
});
await _context.SaveChangesAsync();
}
}
解决方案
推荐阅读
- spring - 运行@SpringBootTest 类时连接没有关闭和堆积
- reactjs - 从 JS 日期对象获取 YYYY-MM-DD 格式的整数月份和年份值?
- r - 在 HTML 输出中使用 summary(CreateTableOne)
- tsql - 如何使用 Union All SELECT 从 SELECT 中选择不同的计数
- batch-file - 使用部分和通配符查找和替换 csv 中的文本,直到第一个分隔符
- authentication - Blazor WASM 身份验证静态 Web 应用程序
- reactjs - MUI v5 - Styled() 和打字稿
- ios - 如何使用 Realm swift 在本地设备上存储资产?
- html - 中心内容被 :before 推到一边
- javascript - JavaScript:在 setTimeout 中定义全局变量