简体   繁体   中英

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

I have two entities witch are related by DataID. What I need is, to get a list, or two lists to pass data to WPF form to display.

    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

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

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

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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