Search code examples
c#entity-framework-corerepository-patternef-database-first

Entity Framework Core database-first selecting specific columns


    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


Solution

  • You can return an anonymous object instead:

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

    This should only select -> send the 2 columns.