I have the following model
public class Account
{
public int Id { get; set; }
public List<Note> Notes { get; set; }
}
I’m trying to query my nhibernate repository to count the number of notes for a specific account.
return this.Data.Where(x => x.Id == accountId).Select(x => x.Notes).Count();
However no matter how many notes there are, it always returns 1.
I am trying to do this in the most efficient way possible without having to get the account object and then count the number of notes.
Can anyone suggest the Linq equivalent of the following SQL.
SELECT Count(*) FROM NoteToAccount WHERE AccountId=?
Where NoteToAccount is a link table which sits between the Account and Note tables.
You are getting back an
IEnumerable<List<Note>>which has one element which is the list of notes for the account.You can use
SelectManyinstead ofSelectto flatten it down into one large entity, or you can use:I am, of course, assuming that accountId is the primary key, so you’ll only ever get one item back. You could also use
Singleinstead ofFirstto ensure you get exactly one item back.