Miguel Moura
Miguel Moura

Reputation: 39374

Get first object in child collection inside projection

I have the following entities:

public class Mark {
  public Int32 Id { get; set; }
  public DateTime Created { get; set; }
  public virtual ICollection<MarkLocalized> MarksLocalized { get; set; }
} // Mark

public class MarkLocalized {
  public Int32 Id { get; set; }
  public String Culture { get; set; }
  public String Name { get; set; }
  public virtual Mark Mark { get; set; }
} // MarkLocalized

Given a culture, for example "en", I need to get all Marks, their localized name for the given culture and map them to a MarkModel:

public class MarkModel {
  public Int32 Id { get; set; }
  public String Name { get; set; }
} // MarkModel

I tried the following:

Context context = new Context();
context.Marks
  .SelectMany(x => x.MarksLocalized, (y, z) =>
    new MarkModel {
      Id = y.Id,
      Name = z.Name,
      Slug = z.Slug
    });

But I need only the MarksLocalized which culture is equal to the given culture.

How can I do this?

Thank you, Miguel

Upvotes: 0

Views: 61

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

You can add Where inside SelectMany:

Context context = new Context();
context.Marks
  .SelectMany(x => x.MarksLocalized.Where(x => x.Culture == "en"), (y, z) =>
    new MarkModel {
      Id = y.Id,
      Name = z.Name,
      Slug = z.Slug
    });

But should be more clear with syntax query:

from m in new Context.Marks
from l in m.MarksLocalized
where l.Culture == "en"
select new MarkModel { m.ID, m.Name, l.Slug }

which should be translated into following query by compiler:

context.Marks
  .SelectMany(x => x.MarksLocalized, (m, l) => new { m, l })
  .Where(x => x.l.Culture == "en")
  .Select(x => new MarkModel { x.m.ID, x.m.Name, x.l.Slug })

which should produce exact same results as first one.

Upvotes: 2

Related Questions