Reputation: 346
I have child entity, and want to include parent field. Query is simple
var item = db.Events
.Where(e => e.Id == eventId)
.Include(e => e.EventItems)
.Include(e => e.ParentObject)
.SingleOrDefault();
However instead of loading whole ParentObject with its complex children, I want only one of it's fields. How should I do this, and do I need to add that field to child entity (right now I have whole parent)
public class EventBase
{
public int Id { get; set; }
[ForeignKey("ParentObject")]
public int ParentId { get; set; }
public Parent Parent { get; set; }
}
Upvotes: 0
Views: 2025
Reputation: 30474
One of the slower parts of database queries is the transfer of data from the database to your local process. Therefore it is very wise not to select any properties you don't plan to use.
Therefore, whenever you see an Include, reconsider your statement. The Include is not the best way for your selections, because it transfers more data than you'll actually use.
Consider for instance a Teacher and Students. The Teacher has a primary key, every Student of this Teacher has a foreign key with a value equal to the Teacher's primary key.
If you'd use Include
to fetch Teachers and their Students, then all foreign keys will be transferred to local memory, which is quite a waste, because you know they all equal the Teacher's primary key.
Back to your question
So you want some properties of the one-and-only event with eventId, you also want some properties of the parentObject of this event, and you want (some) properties of all its EventItems.
Easy! Use Select, and make sure that you only select the properties you really plan to use
var result = db.Events // from all events
.Where(event => event.Id == eventId) // take only the ones with Id == eventId
.Select(event => new // from every remaining event,
{ // select the following properties:
// select only the properties you plan to use, for instance:
Name = event.Name,
Description = event.Description,
// from the one and only parent, select the properties you plan to use
Parent = new
{
Name = event.ParentObject.Name,
Security = event.ParentObject.Security,
},
EventItems = event.EventItems
.Where(eventItem => eventItem.Severity > high)
.Select(eventItem => new
{
// again: only the properties you use!
})
.ToList(),
})
.SingleOrDefault();
Upvotes: 3
Reputation: 89256
With Select(), and an anonymous type. See Projection Operations
var item = db.Events
.Where(e => e.Id == eventId)
.Include(e => e.EventItems)
.Select(e => new {Event=e, ParentDesc=e.Parent.Desc})
.SingleOrDefault();
Upvotes: 1