EF: How to return only a few columns from the database?

Asked

Viewed 33 times

0

I’m having trouble returning a collection of objects from the database with just a few columns selected. I searched several solutions on the web and the vast majority presented the solution below, making a Where and soon after a Select to select the columns desired:

 public override async Task<IEnumerable<KeyType>> GetAllAsync(Guid? userId)
    {
        try
        {
            return await _context.Set<KeyType>()
                .Where(keytype => keytype.UserId.Equals(userId))
                .Select(x => new KeyType
                {
                    x.Name,
                    x.Description,
                    x.UserId
                }).ToListAsync();
        }
        catch (Exception ex)
        {
            throw ex;
        }

But it is giving the error : "It is not possible to initialize the "Keytype" type with a collection initializer because it does not implement "System.Collections.Ienumerable". What will be the mistake? What would be the right type in this case? Thank you.

  • 1

    pq does not create a class with the three properties you need?

  • Well, I thought I’d do Dtos but I thought it would be too much repeat code because it’s too many classes.

1 answer

0

Problem solved: I just changed the Task<IEnumerable<KeyType>> for Task<IEnumerable<dynamic>> and changed the signature on the interface it implements.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.