开发者

LINQ to count number of rows in link table

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 SelectMany instead of Select to flatten it down into one large entity, or you can use:

this.Data.First(x => x.Id == accountId).Notes.Count;

I am, of course, assuming that accountId is the primary key, so you'll only ever get one item back. You could also use Single instead of First to ensure you get exactly one item back.


You want to use

.SelectMany(x => x.Notes)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜