views:

32

answers:

2

Hi - I'd like to get some help on how to formulate this query:

I Have a snapshot of the datamodel relevant to this question at: http://jdsign.dk/media/9221/dbdiagram.png

To the method that should be created the input is a guid userid in the following called inputuserid.

Please help me get: a list of all the subjects that have any note where (note => note.UserId == inputuserid) the subjectlist must also contain all the subjects that are associated with the inputuserid in the Schemas table.

Some subjects may meet both the requirements, but I only want one instance of a subject in the outputsubjectlist.

The outputsubjectlist that is returned to the user, should be loadedwith the notes where (note => note.UserId == inputuserid)

The first part of getting the subjectlist is not that hard I've done it like this: return this.DataContext.Subjects.Where(s => s.Notes.Any(n => n.UserId == userid) || s.Schemas.Any(sc => sc.UserId == userid)).Distinct();

but how do I get the related Notes loaded into the subject?

A: 

Assuming you have the default parent child relationships set up:

var outputsubjectlist = from sub in dc.Subjects
where sub.Notes.Any(note => note.UserId == inputuserid)
    || sub.Schemas.Any(schema => schema.UserId == inputuserid)
select sub
recursive
I might be wrong, but wouldn't a join be more efficient? I've been analyzing the sql code generated by some similar linq expressions a few weeks ago and if I remember find findings correctly, each of your where clauses would result in a subquery.
Adrian Grigore
@Adrian: I really don't know. It would make sense though.
recursive
Thank you for your reply, my problem is that, if I use that query this: "The outputsubjectlist that is returned to the user, should be loadedwith the notes where (note => note.UserId == inputuserid)" isn't met, It only returns the subjects, and not the subjects, with the notes that are specific to the user as children. I've been tring to use LoadWith<Subject>(s => s.Notes.where(...)) but apparently I can't use where, and if I only do LoadWith<Subject>(s => s.Notes) then I return ALL the notes associated with that subject, no matter what the user, and I don't want to do that
Jakob
A: 

It sounds like "recursive" got almost 100%. The missing output is the list of Notes that match the inpuuserid.

Isn't then the answer this:

var outputsubjectlist = from sub in dc.Subjects
where sub.Notes.Any(note => note.UserId == inputuserid)
    || sub.Schemas.Any(schema => schema.UserId == inputuserid)
select new
{
    Subject = sub,
    Notes = sub.Notes.Where(note => note.UserId == inputuserid).ToArray(),
}

(I added to the .ToArray() to force evaluation.)

Enigmativity
what I would like to return is IEnumerable<Subject> with Note childentities that are related to the subject with the specified userid, I tried casting outputsubject list to IEnumerable<Subject>, but it fails
Jakob