2

I'm having some files saved into a MSSQL database using EF core with a structure like

public class UploadedFile
{
    public int Id { get; set; }
    public string Source { get; set; }
    public byte[] Content { get; set; }

I want to be able to load the list of "UploadedFiles" from database without actually reading the Content column from the database. So I can't really use

await _context.UploadedFiles.ToListAsync();

I believe I can use something like bellow with a stored procedure.

_context.Set<UploadedFiles>().FromSql("dbo.spGetUploadedFiles")

But, is there any other way that would not involve using a stored procedure? I can't un-map the column in the model as I need it for insert/read individual items. Thank you.

mslliviu
  • 1,098
  • 2
  • 12
  • 30
  • Does reading a projection violate any of your requirements? e.g. _context.UploadedFiles.Select(uf => new { uf.Id, uf.Source })? – Eric Sep 08 '17 at 18:10
  • @Eric I think you are right, I can do with projection. I will try to actually profile the query, please post it as answer – mslliviu Sep 08 '17 at 18:15

2 Answers2

3

You can basically use .Select({..) to specify which columns you want to return:

public class MyItem
{
    public int Id { get; set; }
    public string Source { get; set; }
}

var data = _context.UploadedFiles
    .Select(p => new MyItem
    {
        Id = p.Id,
        Source = p.Source
    })
    .ToListAsync();

This way you tell EF to generate the select only for those columns and nothing more. You can also select an anonymous object like .Select(p => new { ... }) if you feel like so.

I strongly recommend using strong types.

Cristian Szpisjak
  • 2,429
  • 2
  • 19
  • 32
2

Use a projection:

var results = _context.UploadedFiles.Select(uf => new { uf.Id, uf.Source });
Eric
  • 1,737
  • 1
  • 13
  • 17
  • I ended up with _context.UploadedFiles.Select(up => new UploadedFile() { Id = up.Id, Source = up.Source }).ToListAsync(); as I wanted to result into a UploadedFile object. – mslliviu Sep 08 '17 at 18:18