简体   繁体   English

使用来自分组的Linq查询的数据以及来自另一个表的相关数据创建列表

[英]Create list with data from grouped Linq query plus related data from another table

I have two entities witch are related by DataID. 我有两个实体女巫是通过DataID关联的。 What I need is, to get a list, or two lists to pass data to WPF form to display. 我需要的是获取一个列表或两个列表以将数据传递到WPF表单进行显示。

    public class Journal
    {
    [Key]
    public int ID {get; set;}


    public int DataID {get; set;}
[ForeignKey("DataID")]   
 public virtual JournalData JournalData { get; set; }
    }

    Public class JournalData
    {
    [Key]
    public int DataID {get; set;}
    public string Field1 { get; set; }
    public string Field2 { get; set; }
    }

First of all I created a lists 
List<Journal>
List<JournalData>

When I'v tried to get data from Journal grouped by DataID 当我尝试从按DataID分组的日记中获取数据时

List<Journal> result = query
                    .GroupBy(t => t.DataID)
                    .Select(g => new { DataID = g.Key})
                    .ToList()
                    .Select(t => new Journal() { DatatID = t.DataID })
                    .ToList();

I have only DataID and now I want to add data from JournalData where DataID =t.DataID 我只有DataID,现在我想从JournalData添加数据,其中DataID = t.DataID

Could You please help me? 请你帮助我好吗? Mabe the is a way to get related data through relationship? 也许是通过关系获取相关数据的一种方法?

You probably need to include JournalData in your query 您可能需要在查询中include JournalData

you will need to add following namespace 您将需要添加以下名称空间

using System.Data.Entity;

Something like this (not tested) 像这样的东西(未经测试)

List<Journal> result = query
                .Include(t => t.JournalData)
                .GroupBy(t => t.DataID)
                .Select(g => new { DataID = g.Key, JornalData = g.JournalData})
                .ToList()
                .Select(t => new Journal() { DatatID = t.DataID, JournalData = t.JournalData })
                .ToList();

EDIT 编辑

var result = query.Include(t => t.JournalData)
                  .GroupBy(g => g.DataID)                     
                  .Select(g => new { DataID = g.Key, JournalData = g.Select(j => j.JournalData) })
                  .ToList();

EDIT2 if you want field1, field2 next to DataID something like this EDIT2,如果您想在dataID旁边输入field1,field2就像这样

var result = journals.GroupBy(g => g.DataID)
                .Select(g => new
                {
                    DataID = g.Key,                     
                    Fields = g.Select(j => new { Field1 = j.JournalData.Field1, Field2 = j.JournalData.Field2}) 
                })                  
                .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM