EntityFramework Core 2.0 skip loading column

元气小坏坏 提交于 2019-12-11 00:45:40

问题


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:


Use a projection:

var results = _context.UploadedFiles.Select(uf => new { uf.Id, uf.Source });



回答2:


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.



来源:https://stackoverflow.com/questions/46122299/entityframework-core-2-0-skip-loading-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!