Reputation: 35
So I am trying to filter the modules object list by userID
of the currently logged in user. After that I am trying to take the moduleID
of those selected object.
Using that I want to filter the reports list to only those that contain a moduleID
that matches any of the the previously obtained list of moduleID
.
I'm not that particularly knowledgeable on Linq and this is what I came up with:
var name = User.Identity.GetUserName();
//gets the currently logged in user:
ApplicationUser currentUser =
(ApplicationUser)db.Users.Single(x => x.UserName == name);
//gets moduleID's for modules owned by current user:
var modules = (from i in db.Modules
where i.User == currentUser
select i.ModuleID);
var Reports = from u in db.Reports
where u.moduleID == modules
select u;
I'm having problems with the last portion trying to incorporate the contains method into the statement.
Any help would be appreciated.
Upvotes: 1
Views: 2315
Reputation: 1186
Use the navigation properties if you have a one to many relation you could do directly in your Where clause:
var name = User.Identity.GetUserName();
var Reports = db.Reports.Where(x => x.Module.User.Name == name);
Upvotes: 0
Reputation: 11
You're close. In Linq its a little backwards from standard SQL. In its case you want to see if the report's module id is contained in the list of modules, so it would look like this:
var Reports = from u in db.Reports
where modules.Contains(u.moduleID)
select u;
Upvotes: 0
Reputation: 9548
You could simplify the multiple queries to one if I'm inferring your table structure correctly:
var name = User.Identity.GetUserName();
var reports = from r in db.Reports
join m in db.Modules on r.moduleID equals m.ModuleID
where m.User.UserName == name
select r;
Upvotes: 1
Reputation: 895
You're on the right track.
var Reports = from u in db.Reports
where modules.Contains(u.moduleID)
select u;
Or using lambda:
var reports = db.Reports.Where(u => modules.Contains(u));
Upvotes: 0
Reputation: 14477
You can't compare a int
to a IEnumerable<int>
. However you can check if the moduleID
is found within the modules
like this :
where modules.Contains(u.moduleID)
Upvotes: 0