I have two entities: User
and Notice
, they are linked together via the DismissedNoticeToUser
table (UserId
and NoticeId
are the respective columns).
Here's my FluentNHibernate mapping for the User
class:
mapping.HasManyToMany<Notice>(u => u.DismissedNotices)
.Table("DismissedNoticeToUser")
.ParentKeyColumn("UserId")
.ChildKeyColumn("NoticeId")
.Inverse();
Every time a use "dismisses" a notice, a pair of the User.Id
and Notice.Id
are added to the DismissedNoticeToUser
class. This is easy in code:
var notice = this.session.Load<Notice>(noticeId);
var user = this.session.Load<User>(this.userSession.Id);
user.DismissedNotices.Add(notice);
If I want to list all notices not dismissed by the user, I write something like this in raw SQL:
select * from [Notice]
where Id not in
(select NoticeId from [DismissedNoticeToUser] where UserId=@userId)
However, I'm not really sure how to do the same thing using NHibernate. I've tried the following, but it does a left join on the user's notices as a separate query.
this.session.Query<Notice>().Where(n => !user.DismissedNotices.Contains(n));
I could drop down and use NHibernate to write raw SQL, but I feel as though I'm probably missing something. I don't care which NHibernate query API I use.