Simas Pruselaitis
Simas Pruselaitis

Reputation: 23

LINQ string casting error when returning a byte array

I'm trying to store hashes and salts in a database using entity framework. But when I try to call this code to return one of the salts.

var salt = (from u in db.Users
            join p in db.Passwords on u.Name equals p.UserName
            where u.Name == username
            select p.Salt).First();

I get thrown this exception: System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.Byte[]'.'

My Password entity looks like this:

    class Password
    {
        [Key]
        public string UserName { get; set; }
        public byte[] Hash { get; set; }
        public byte[] Salt { get; set; }
        public User User{ get; set;}
    }

Upvotes: 0

Views: 442

Answers (1)

Tanveer Badar
Tanveer Badar

Reputation: 5523

Your table's columns are likely varchar or something similar, rather than binary/varbinary data types - or whatever term your database server uses for storing binary data.

If you are using EF core, then see value converters. There's a StringToBytesConverter available.

Upvotes: 2

Related Questions