- I want my Edit method in my CRUD page to not allow duplicate email entries. If a user tries to enter an email that already exists when editing, then the user should receive an error message. So far I have this. Would anyone be able to help me out :)
EDIT METHOD
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);
}
}
CREATE METHOD
- I want my Create method in my crud page to not allow duplicate email entries. If a user tries to enter an email that already exists when creating, then the user should receive an error message. So far I have this.
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();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…