Linq选择映射为多对多的项目?

时间:2015-03-25 18:49:04

标签: c# linq entity-framework

我正在尝试为表构建一个select查询,同时只包含连接的Primary Key值而没有属性。我设法获得了选择查询,但我无法弄清楚如何获取select语句。基本上我试图从DiploReCertificate实体中的ProgramID获取DegreeRelationship表中的DegreeID列表(映射而不是实体)。然后我想获得学位名称。

我对映射表的上下文如下所示:

modelBuilder.Entity<Degree>()
                .HasMany(e => e.DiplomaCertificates)
                .WithMany(e => e.Degrees)
                .Map(m => m.ToTable("DegreeRelationship").MapLeftKey("DegreeID").MapRightKey("ProgramID"));

基本上,我正在尝试将值放入此对象中:

public class DegreeRelationshipInfo
    {
        public int ProgramID { get; set; }
        public int DegreeID { get; set; }
        public string LinkedProgramName { get; set; }
    }

我正在尝试这样的方法,但我不确定如何写这个(这是完全错误的):

[DataObjectMethod(DataObjectMethodType.Select, false)]
        public List<DegreeRelationshipInfo> Select_DegRel(int programID)
        {
            using (Pathway_Model context = new Pathway_Model())
            {
                var results = from data in context.Degrees
                              where data.DiplomaCertificates.Where(x => x.ProgramID == programID)
                              select new DegreeRelationshipInfo
                              {
                                  ProgramID = data.ProgramID,
                                  // no idea how to get this value.... 
                              };
                return results.ToList();
            }
        }

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

SelectMany选择实体并收集其关键值:

from data in context.Degrees
from cert in data.DiplomaCertificates
select new DegreeRelationshipInfo
{
    ProgramID = data.ProgramID,
    DegreeID = cert.DegreeID,
    LinkedProgramName = data.Name // I guess...
}

from - from构造编译为SelectMany,但语法更易读。