Creating a LINQ select from multiple tables

前端 未结 5 583
孤街浪徒
孤街浪徒 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:36

    You can use anonymous types for this, i.e.:

    var pageObject = (from op in db.ObjectPermissions
                      join pg in db.Pages on op.ObjectPermissionName equals page.PageName
                      where pg.PageID == page.PageID
                      select new { pg, op }).SingleOrDefault();
    

    This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:-

    var pageObject = (from op in db.ObjectPermissions
                      join pg in db.Pages on op.ObjectPermissionName equals page.PageName
                      where pg.PageID == page.PageID
                      select new
                      {
                          PermissionName = pg, 
                          ObjectPermission = op
                      }).SingleOrDefault();
    

    This will enable you to say:-

    if (pageObject.PermissionName.FooBar == "golden goose") Application.Exit();
    

    For example :-)

提交回复
热议问题