在投影中获取子集合中的第一个对象

时间:2014-03-20 22:01:03

标签: linq entity-framework

我有以下实体:

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

鉴于文化,例如“en”,我需要获取所有Marks,他们为给定文化的本地化名称并将它们映射到MarkModel:

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

我尝试了以下内容:

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

但我只需要MarksLocalized哪种文化与给定的文化相同。

我该怎么做?

谢谢你, 米格尔

1 个答案:

答案 0 :(得分:2)

您可以在Where内添加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
    });

但是语法查询应该更清楚:

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

应该由编译器翻译成以下查询:

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 })

应该产生与第一个完全相同的结果。