0

Let's say I have 2 entities (1-to-many) relation: Component and Part like so:

public Component
{
   string CompName { get; set; }
   byte[] CompBlob { get; set; }
   ICollection<Part> Parts { get; set; }
}
public Part
{
   string PartName { get; set; }
   byte[] PartBlob { get; set; }
}

When I load a Component, I want to always load its Parts for this particular entity.

I want to know how to select / project a list of components so that EF will not load additional inner properties (eg: only CompName and PartName to be loaded but not CompBlob and inner PartBlob).

Maybe something like below, but how to apply a selector for Parts?

//
dbContext.Components.Include(c => c.Parts).Where(filterComponents).Select(.?.)
//

If needed, I have LazyLoadingEnabled set to false

Learner
  • 3,297
  • 4
  • 37
  • 62

2 Answers2

2

If you're using entity framework, you need to add primary key for each entity, like below:

public class Component
{
    public int Id { get; set; }
    public string CompName { get; set; }
    public byte[] CompBlob { get; set; }
    public ICollection<Part> Parts { get; set; }
}
public class Part
{
    public int Id { get; set; }
    public string PartName { get; set; }
    public byte[] PartBlob { get; set; }
}

Then make the query like:

LazyLoading Disable Case:

var result = dbContext.Components.Include("Parts").Select(m => new 
             {m.CompName, PartNames = m.Parts.Select(n => n.PartName)}).ToList();

LazyLoading Enabled Case:

 var result = dbContext.Components.Select(m => new 
         {m.CompName, PartNames = m.Parts.Select(n => n.PartName)}).ToList();
Lin
  • 15,078
  • 4
  • 47
  • 49
  • Lin: Would it be possible to have a custom dynamic selector? ".Select(selector)" where selector is created programmatically? I am not quite sure how to achieve that. – Learner Feb 10 '14 at 09:24
  • hi @Cristi, take a look at the following link, it's about how to select fields dynamically. http://stackoverflow.com/questions/16516971/linq-dynamic-select – Lin Feb 10 '14 at 20:48
1

If I understand you correctly...

var query = dbContext.Components.Select(x => new {
        CompName = x.CompName,
        Parts = x.Parts.Select(p => p.PartName)
    }).ToList();

Add additional filters and selectors as you require. You may / may not need the Include statement (.Include("Parts"))

Jon Bellamy
  • 3,333
  • 20
  • 23