1

请考虑下表。

表:文档

docID, docNr, docScanTime
10, 99, 2012-08-02
11, 98, 2012-08-02
12, 97, 2012-08-02
13, 96, 2012-08-02
14, 95, 2012-08-02

表:DocumentFlag

用户 ID、文档 ID、isDelete、isArchive 41、10、1
、NULL 42、11
、NULL、1

Document 表中有 5 行,DocumentFlag 表中有 2 行。我正在使用以下 Linq 语句来获取文档列表。

List<Document> docList = new List<Document>();
using (AppDataContext context = data.GetDataContext())
{
  docList = (from d in context.Documents
             join f in context.DocumentFlags on d.docID equals f.docID
             where f.usrID == userID
             select new Document
             {
                 DocID = d.docID,
                 DocNr = d.docNr,
                 ScanTime = d.docScanTime.Value,
                 UserID = f.userID,
                 IsDelete = f.isDelete.Value,
                 IsArchive = f.isArchive.Value,
              }).ToList<Document>();
}

public class Document
{
  public int DocID {get; set;}
  public int DocNr {get; set;}
  public DateTime DocScanTime {get; set;}
  public int UserID {get; set;}
  public byte IsDelete {get; set;}
  public byte IsArchive {get; set;}
}

但问题是我只得到了 DocumentFlag 中的两行。我想获取 Document 中的所有行以及列表中 DocumentFlag 中的信息。如果 DocumentFlag 不包含有关文档的信息,则它可以将 null 存储在 isDelete 或 isArchive 中。

有任何想法吗?

4

2 回答 2

3

您想在 Linq 中进行左外连接。我的语法有点生疏,但我认为它看起来像这样:

  docList = (from d in context.Documents
         join f in context.DocumentFlags on d.docID equals f.docID into ftmp
         where f.usrID == userID
         from f in ftmp.DefaultIfEmpty()
         select new Document
         {
             DocID = d.docID,
             DocNr = d.docNr,
             ScanTime = d.docScanTime.Value,
             UserID = f.userID,
             IsDelete = f.isDelete.Value,
             IsArchive = f.isArchive.Value,
          }).ToList<Document>();

以下文章可能会有所帮助: https ://smehrozalam.wordpress.com/2009/06/10/c-left-outer-joins-with-linq/

于 2012-08-02T14:37:38.137 回答
1

您正在尝试的是 LINQ 中的 LEFT OUTER JOIN。

试试这个:

using (AppDataContext context = data.GetDataContext())
{
    docList = (from d in context.Documents
                join f in context.DocumentFlags on d.docID equals f.docID into flg
                where f.usrID == userID 
                from fff in flg.DefaultIfEmpty()
                select new Document
                {
                    DocID = d.docID,
                    DocNr = d.docNr,
                    ScanTime = d.docScanTime.Value,
                    UserID = fff.userID,
                    IsDelete = fff.isDelete.Value,
                    IsArchive = fff.isArchive.Value,
                }).ToList<Document>();
}
于 2012-08-02T14:52:17.320 回答