Creating a LINQ select from multiple tables

前端 未结 5 566
孤街浪徒
孤街浪徒 2020-12-02 09:11

This query works great:

var pageObject = (from op in db.ObjectPermissions
                  join pg in db.Pages on op.ObjectPermissionName equals page.PageNa         


        
5条回答
  •  死守一世寂寞
    2020-12-02 09:35

    If you don't want to use anonymous types b/c let's say you're passing the object to another method, you can use the LoadWith load option to load associated data. It requires that your tables are associated either through foreign keys or in your Linq-to-SQL dbml model.

    db.DeferredLoadingEnabled = false;
    DataLoadOptions dlo = new DataLoadOptions();
    dlo.LoadWith(op => op.Pages)
    db.LoadOptions = dlo;
    
    var pageObject = from op in db.ObjectPermissions
             select op;
    
    // no join needed
    

    Then you can call

    pageObject.Pages.PageID
    

    Depending on what your data looks like, you'd probably want to do this the other way around,

    DataLoadOptions dlo = new DataLoadOptions();
    dlo.LoadWith(p => p.ObjectPermissions)
    db.LoadOptions = dlo;
    
    var pageObject = from p in db.Pages
                     select p;
    
    // no join needed
    
    var objectPermissionName = pageObject.ObjectPermissions.ObjectPermissionName;
    

提交回复
热议问题