Home > Enterprise >  Entity Framework Core database-first selecting specific columns
Entity Framework Core database-first selecting specific columns

Time:11-06

    public Tbl016 CheckLoginCredentials(string UserName, string Password)
    {
        return
            context.Agents
            .Where(x => x.LoginName == UserName && x.LoginPassword == Password)
            .Select(x => new Tbl016
            {
                LoginName = x.LoginName,
                LoginPassword = x.LoginPassword
            })
            .FirstOrDefault();
    }

I'm developing an Entity Framework Core API using database-first approach and using a repository design pattern. In the above function I'm trying to retrieve specific columns from the database, but unfortunately, when I run the code, the response body brings data from all the columns in the table.

What I've tried so far is the .Select new expression but it is not working.

Result

CodePudding user response:

You can return an anonymous object instead:

.Select(x => new {
    x.LoginName,
    x.LoginPassword
}).FirstOrDefault();

This should only select -> send the 2 columns.

CodePudding user response:

Thanks to @mxmissile the problem is solved I changed the return type of the method to dynamic instead of (an Object of the table). then I returned data anonymously in the .Select() method The full code is:

public dynamic CheckLoginCredentials(string UserName, string Password)
{
    return context.Agents
        .Where(x => x.LoginName == UserName && x.LoginPassword == Password)
        .Select(x => new {
            x.LoginName,
            x.LoginPassword
        })
        .FirstOrDefault();
}
  • Related