tags:

views:

91

answers:

3
+1  Q: 

LINQ to SQL query

Hi,

I have a User entity which represents a User table in my database. This table has a field called ManagerID which references another User record (basically an employee to manager mapping). Each User will also have a reference to another table which can have multiple entries, for the sake of this example we will call it Records.

So the basic rule is every user can have multiple Records and every user can manage a team of other Users.

So as a small example of what I need to do:

User manager = Repository.FindUser('12345');
List<Record> TeamRecordCollection = new List<Record>();

// add the managers records to the team collection
var managerRecords = GetRecords(manager, DateTime.Today);
TeamRecordCollection.AddRange(managerRecords);

// add each individual team members records
foreach (var user in manager.TeamMembers)
{
    var records = GetRecords(user, DateTime.Today);
    TeamRecordCollection.AddRange(records);
}

...

private IEnumerable<Record> GetRecords(User user, DateTime date)
{
    var records = from rec in user.Records
                  where rec.DateSubmitted == date
                  select rec;
    return records.AsEnumerable();
}

// the above code isn't tested it is just a sample idea

So what I would like to know is:

a) Can this be done in the one L2S statement?
b) Would it be more efficient than the current way?

+1  A: 

You can use sub-selects or joins:
http://stackoverflow.com/questions/527819/linq-sub-select
to get rid of iterations

u3k
+2  A: 

How about something like;

var records = from rec in _DB.Records
              from user in _DB.Users.Where(x => x.ManagerId == managerId ||
                                                x.Id == managerId)
              where rec.UserId == user.Id
              select rec;
Kirschstein
I think this looks a good shout, although the Where statement would have to change to user.ManagerID == managerId || user.ID == managerID) as the manager can have records aswell.
James
@James: fixed, I think this should work. No idea what the performance implications are though, perhaps do some benchmark tests?
Kirschstein
Had to tweak it a little but all in all this helped me sort it out, thanks. Yeah I will do some benchmarking aswell to test whether it is the most efficient way.
James
A: 

Also,

Once you find a LINQ2SQL solution for this one, make sure to use SQL profiler to see the execution plan and tweak as needed.

HTH

unclepaul84