Linq将sql转换为对象列表

时间:2013-01-07 12:57:39

标签: c# linq-to-sql

请考虑以下表格:

TblDocument

docID,  levelID, name 
101,    201,     AAA 
102,    201,     BBB 
103,    201,     CCC 
104,    202,     DDD 
105,    202,     EEE 

的tblpage

pgID, docID, pgNo
1,    101,   1
2,    102,   1
3,    102,   2
4,    103,   1
5,    104,   1
6,    105,   1

TblFieldName

fieldNameID, levelID, fieldName  
1,           201,     WrittenBy  
2,           201,     VerifiedBy 
3,           201,     DocumentName

TblFieldValue

docID,  fieldNameID, fieldValue 
101,    1,           James 
101,    2,           Bond  
101,    3,           Essay on something  
102,    1,           Krister
102,    2,           Holm
102,    3,           Dame it or not!  

public class Document
{
  public int DocID {get; set;}
  public int LevelID {get; set;}
  public string Name {get; set;}

  public List<Field> Metadata
  {
     get { return (_fields); }
     set { _fields = value; }
  }       
  private List<Field> _fields = new List<Field>();
}


public class Field
    {
      public FieldNameID {get; set;}
      public FieldName {get; set;}
      public FieldValue {get; set;}
    }

现在,我正在尝试使用linq从数据库中获取数据,该工作正常。

using (DBDataContext context = new DBDataContext())
{
  List<Document> doc  = (from d in context.TblDocuments
     join p in context.TblPages on d.docID equals p.docID into dpgrp
     from dp in dpgrp.Where(f => f.docID == d.docID).DefaultIfEmpty()
     where d.levelID == 201
     select new Document
     {
       DocumentID = d.docID,
       LevelID = d.levID
     }).ToList<Document>();
 }

有人可以帮助我如何在列表中获取字段值?

using (DBDataContext context = new DBDataContext())
{
  List<Document> doc  = (from d in context.TblDocuments
     join p in context.TblPages on d.docID equals p.docID into dpgrp
     from dp in dpgrp.Where(f => f.docID == d.docID).DefaultIfEmpty()
     where d.levID == 201
     select new Document
     {
       DocumentID = d.docID,
       LevelID = d.levID
       Metadata = ???????            // how to achieve this? as it is a list
     }).ToList<Document>();
 }

1 个答案:

答案 0 :(得分:0)

我建议将DataLoadOptions用于L2S

options.LoadWith<Document>(d => d.Metadata);