简体   繁体   中英

Entity Framework - Include Properties, but exclude single columns

Let's say I have a list of items, which each can reference a list of documents (and other stuff). In Entity Framework I can get the list like that:

var items = context.Items
        .Include(i => i.Documents)
        .Include(i => i.OtherProperty)
        .ToList()

Now this includes all columns from documents. Is it possible to exclude one of these columns (eg. the "Data"-column which stores the complete document as binary)?
Something like this:

var items = context.Items
        .Include(i => i.Documents)
            .ButExclude(d => d.Data)
        .Include(i => i.OtherProperty)
        .ToList()

I know that I could use.Select() and create an object without the data property, but since I use a lot of foreign keys I would rather like to use includes.
I also know that it is better to separate the document's metadata from the actual content, but well... I haven't...

Make another model that doesnt include data that you dont need

public class CreateAndUpdatePropertiesModel
{
    public string Documents { get; set; }
    public string OtherProperties { get; set; }
}

And then use this model as a property in primary model:

public class ExampleModel
{
    public string Documents { get; set; }
    public string Data { get; set; }
    public string OtherProperties { get; set; }

    // And then add the CreateAndUpdateProperties model as a property
    public CreateAndUpdateProperties { get; set; }
}

then only Include wanted data .Include(s => s.CreateAndUpdateProperties)

This Question was previously asked many times:

Exclude columns getting data with Entity Framework

  • Added as answer due to low amount of rep(cant comment)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM