简体   繁体   中英

Entity Framework, Getting part of an entity

I have an entity with one field I do not want to return sometimes.

I am setting it to null right now. Is there a way to specify this in the query itself instead of clearing it out like I am here?

    public async Task<IQueryable<XYZXY>> GetStuff()
    {
            histories =
                _db.Stuffs
                    .Where(n => n.NationId == User.NationId)
                    .OrderBy(x => x.DateSent);
            await histories.ForEachAsync(d => d.Attachment = null);
            return histories;

    }

What you are looking for is called projection, this is what stuff do you want to project into your result set from the server.

In EF projection is done by a combination of the select line of your query and any Includes which you have done.

If attachment is a second table accessed by a navigation property it wont be returned by your current query (IE it will be null) unless you are doing lazy loading (normally signified by the virtual keyword on the nav property eg public virtual Attachment Attachment {get;set;} ). If attachment is a column projection is more complicated

You have 2 options, use an annonomous type eg:

_db.Stuffs
   .Where(n => n.NationId == User.NationId)
   .OrderBy(x => x.DateSent)
   .Select(x=> new { A = x.A, B = x.B .... /*Dont list attachment*/});

or reuse the existing object

_db.Stuffs
   .Where(n => n.NationId == User.NationId)
   .OrderBy(x => x.DateSent)
   .Select(x=> new Stuff { A = x.A, B = x.B .... /*Dont list attachment*/});

Do note custom projections will not be tracked so changing a property and calling save wont work.

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