Creating a LINQ select from multiple tables
C#LinqC# Problem Overview
This query works great:
var pageObject = (from op in db.ObjectPermissions
join pg in db.Pages on op.ObjectPermissionName equals page.PageName
where pg.PageID == page.PageID
select op)
.SingleOrDefault();
I get a new type with my 'op' fields. Now I want to retrieve my 'pg' fields as well, but
select op, pg).SingleOrDefault();
doesn't work.
How can I select everything from both tables so that they appear in my new pageObject type?
C# Solutions
Solution 1 - C#
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 :-)
Solution 2 - C#
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<ObjectPermissions>(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<Pages>(p => p.ObjectPermissions)
db.LoadOptions = dlo;
var pageObject = from p in db.Pages
select p;
// no join needed
var objectPermissionName = pageObject.ObjectPermissions.ObjectPermissionName;
Solution 3 - C#
Solution 4 - C#
If the anonymous type causes trouble for you, you can create a simple data class:
public class PermissionsAndPages
{
public ObjectPermissions Permissions {get;set}
public Pages Pages {get;set}
}
and then in your query:
select new PermissionsAndPages { Permissions = op, Page = pg };
Then you can pass this around:
return queryResult.SingleOrDefault(); // as PermissionsAndPages
Solution 5 - C#
change
select op)
to
select new { op, pg })