Skip to main content
 首页 » 编程设计

c#之Linq to sql连接

2024年02月20日16小虾米

请考虑下表。

表:文档

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

表:文档标志

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

Document 表中有五行,DocumentFlag 表中有两行。我正在使用以下 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 中。

有什么想法吗?

请您参考如下方法:

您想在 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/