How to exclude one "column" in .ToListAsync() using EF Core?

asp.net-web-api c# entity-framework-core

Question

I have this return code from an async function:

return await _context.Models.ToListAsync();

That is successful in returning this:

[
    { 
        "id":"id",
        "name":"name",
        "url":"url",
        "components":[]
    }
]

Now, I want NOT to show the components like this.

[
    { 
        "id":"id",
        "name":"name",
        "url":"url"
    }
]

So far, I tried:

return await _context.Models.Select( p => new Model {
    Id = p.Id, Name = p.Name, Url = p.Url 
}).ToListAsync();

But it will still show components and only do nullify its value.

1
0
9/4/2019 5:42:30 AM

Accepted Answer

That's because you create a new model and event if you don't provide the value the compiler gives it the default value.so you need to either create a new class and remove the property from it or you need to populate it dynamically and change your code to something like this:

return await _context.Models.Select( p => new {
    Id = p.Id, Name = p.Name, Url = p.Url 
}).ToListAsync();
1
9/4/2019 5:47:30 AM

Popular Answer

You can either use anonymous types like this:

return await _context.Models                    
                 .Select(p => new {
                     p.Id,
                     p.Name        
                 });

Or create a DTO with all the properties you need except the components property.

public class DTO
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Url { get; set; }
}

Then:

.Select(p => new DTO {
               Id = p.Id,
               Name = p.Name,
               Url = p.Url
           });


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow