Linq中的字节转换

时间:2015-08-03 13:50:00

标签: 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是字节列,我从mobile传递为字符串。在这种情况下如何处理这个。请帮我做这个

1 个答案:

答案 0 :(得分:0)

在查找客户时无需检查密码。那是因为你正在处理一个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."
        };
    }

祝你好运。