首页 > 解决方案 > 验证服务 ASP.NET CORE MVC (c#) 中的重复电子邮件条目

问题描述

  1. 我希望我的 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);
            }
        }

创建方法

  1. 我希望我的 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();
            }
        }

标签: c#validationasp.net-core

解决方案


推荐阅读