c# - Linq 中的字节转换

标签 c# mysql linq

请在 Linq 中帮助我。我对 linq 完全陌生。请参阅下面我的代码。

    public Entities.ServiceResult<Customer> CustomerChangePassword(string CustomerId, string OldPassword, string NewPassword)
    {
        long _customerId = Convert.ToInt32(CustomerId);
        byte _oldPassword = Convert.ToByte(OldPassword);
        var _result = (from c in context.customers where (c.CustomerId == _customerId && c.Password == _oldPassword) select c.Password.Single).SingleOrDefault();

        if (_result != null)
        {
            string newpassword;
            newpassword = Convert.ToString(_result.Password);
            newpassword = NewPassword;
            context.SaveChanges();
            return new Entities.ServiceResult<Customer>
            {
                ErrorState = 0,
                Message = "Password Changed Successfully."
            };
        }
        else
        {
            return new Entities.ServiceResult<Customer>
            {
                ErrorState = 1,
                Message = "Old Password Is Wrong."
            };
        }
    }

上面的代码我正在执行更改密码功能。在此代码中,c.Password 是字节列,我从移动设备作为字符串传递。在这种情况下如何处理。请帮我做到这一点

最佳答案

寻找客户无需检查密码。那是因为你正在处理一个 IQueriable 并且你不能在那里轻松地完成这种奇怪的工作。此外,您还应该更改密码,以告诉上下文为您保存密码。 还要考虑将字符串转换为字节数组的代码。 使用 SequenceEqual 方法可以检查两个数组的相等性。

我希望以下代码有帮助:

    public Entities.ServiceResult<Customer> CustomerChangePassword(string CustomerId, string OldPassword, string NewPassword)
    {
        long _customerId = Convert.ToInt32(CustomerId);
        byte[] _oldPassword = Encoding.ASCII.GetBytes(OldPassword);
        var _result = from c in context.customers where (c.CustomerId == _customerId) select c;

        if (_result == null || _result.Count() == 0)
        {
            return new Entities.ServiceResult<Customer>
            {
                ErrorState = 1,
                Message = "User does not exists."
            };
        }

        var customer = _result.First();
        if (!customer.Password.SequenceEqual(_oldPassword))
        {
            return new Entities.ServiceResult<Customer>
            {
                ErrorState = 1,
                Message = "Old Password Is Wrong."
            };
        }
        customer.Password = Encoding.ASCII.GetBytes(NewPassword);
        context.SaveChanges();
        return new Entities.ServiceResult<Customer>
        {
            ErrorState = 0,
            Message = "Password Changed Successfully."
        };
    }

祝你好运。

关于c# - Linq 中的字节转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31789114/

相关文章:

c# - 使用 Ajax 将 json 从 Javascript 返回到 aspx

c# - 在 C# 中将证书安装到 Windows 本地用户证书存储区

c# - 将 linq 连接的左侧或右侧填充为相同的行数

c# - Linq 扩展方法 - GetYearWeekFormat 扩展

c# - CloudBlobContainer.ListBlobs() 中如何使用前缀参数从 Azure Blob 存储中的虚拟文件夹获取文件

c# - 进度条没有更新

php - mysql语句错误

mysql - 根据条件删除 SQL 数据库中的重复项

mysql - FireDAC,将 "secure-auth=OFF"传递给客户端库

C# Linq OrderBy 过滤 null 或空值到最后