EntityFramework Core 2.0 skip loading column

.net-core c# entity-framework entity-framework-core

Question

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.

1
2
9/8/2017 6:07:46 PM

Accepted Answer

Use a projection:

var results = _context.UploadedFiles.Select(uf => new { uf.Id, uf.Source });
2
9/8/2017 6:17:13 PM

Popular Answer

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.



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