Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

validation - Validate duplicate email entries in service ASP.NET CORE MVC (c#)

  1. 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

  1. 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();
            }
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...