Linq查询实体和分组依据

时间:2014-08-18 13:41:47

标签: linq ef-code-first

我有如下所示的实体(使用带有存储库模式的.NET代码优先):

public abstract class BaseContent : Entity
{
    public Guid ID { get; set; }
    public virtual ICollection<AssignedMedia> AssignedMedias { get; set; }
}

public partial class Library : BaseContent
{
    public Library()
    {
        this.AssignedMedias = new List<AssignedMedia>();
    }
}

public class Media : BaseContent
{
    public Media()
    {
        this.AssignedMedias = new List<AssignedMedia>();
    }
}

public class AssignedMedia : Entity
{
    public int ID { get; set; }

    //BaseContent reference ID
    public Guid AssignedId { get; set; }

    public Guid MediaId { get; set; }

    public virtual Media Media { get; set; }
    public virtual BaseContent BaseContent { get; set; }
}

然后我尝试获取查询(作为Dictionary&lt; string,List&lt; Media&gt;&gt;)作为分组依据! 对于实例:

var list = from bc in Libraries
    join a in AssignedMedias on bc.ID equals a.AssignedId
    join m in Medias on a.MediaId equals m.ID
    select new {
        LibraryName = bc.Name, MediaList = ??? 
    };

1 个答案:

答案 0 :(得分:1)

当您已正确映射实体关联时,您不需要使用join。您可以像这样编写查询:

var libraryAssignedMedia = Libraries.ToDictionary(
    l => l.Name, // Key selection.
    l => l.AssignedMedias.Select(am => am.Media)); // Value selection.