Search code examples
c#linqentity-framework-coreasp.net-core-webapi

How to use custom methods in LINQ query


I have the following issue: I am currently working on an ASP.NET Core / Entity Framework Core backend and have the problem that I need to use a custom method in LINQ query and getting a error when doing this.

I have researched and found out that it is possible to write custom functions, that will be translated to SQL, but I think that there is not a big scope for doing this (e.g: SQL will not be able to use libraries and hash strings).

Another way that I have heard of is to convert my database to an enumerable and then apply my custom methods on it, which works, but is not that performant, because I am saving my whole database in my memory, which gets very slow when having a huge amount of data.

So my question: is there is a well performing solution to use custom methods in LINQ queries?

My detailed problem is, that I have saved my salted passwords hashed in my database and when someone want s to log in to his account I have to compare the password in the database with the salt + user password input, that has to get hashed in my where clause. It would work if I wouldn't use salts, because then, I would only have to hash the user input, which is not column of the database.


Solution

  • What you should do is - calculate the hash and salt in the backend, and use the computed hash in your WHERE statement. In this case you don't need to call your methods from SQL equally you don't need to pull entire db (or table) into memory to compute hash.

    As I don't know your code, the pseudo-code approach would be:

        var user = service.GetUserByEmail(email);
    if (user == null) {
    //Invalid User
    }
        var hash = ComputeHash(user.Salt, inputPwd);
        
     if(user.PasswordHash == hash) {
    //User is logged in
    } else {
    //Invalid Password or email
    }