2010-05-11 70 views
0

好的傢伙(和gals),這個人一直在逼我整夜,我正在尋求你的集體智慧來尋求幫助。使用Linq-To-NHibernate進行多對多查詢

我用流利的NHibernate和LINQ到NHibernate的我的數據訪問的故事,我有以下簡單的DB結構:

CREATE TABLE [dbo].[Classes](
[Id] [bigint] IDENTITY(1,1) NOT NULL, 
[Name] [nvarchar](100) NOT NULL, 
[StartDate] [datetime2](7) NOT NULL, 
[EndDate] [datetime2](7) NOT NULL, 
CONSTRAINT [PK_Classes] PRIMARY KEY CLUSTERED 
(
[Id] ASC 
) 

CREATE TABLE [dbo].[Sections](
[Id] [bigint] IDENTITY(1,1) NOT NULL, 
[ClassId] [bigint] NOT NULL, 
[InternalCode] [varchar](10) NOT NULL, 
CONSTRAINT [PK_Sections] PRIMARY KEY CLUSTERED 
(
[Id] ASC 
) 

CREATE TABLE [dbo].[SectionStudents](
[SectionId] [bigint] NOT NULL, 
[UserId] [uniqueidentifier] NOT NULL, 
CONSTRAINT [PK_SectionStudents] PRIMARY KEY CLUSTERED 
(
[SectionId] ASC, 
[UserId] ASC 
) 

CREATE TABLE [dbo].[aspnet_Users](
[ApplicationId] [uniqueidentifier] NOT NULL, 
[UserId] [uniqueidentifier] NOT NULL, 
[UserName] [nvarchar](256) NOT NULL, 
[LoweredUserName] [nvarchar](256) NOT NULL, 
[MobileAlias] [nvarchar](16) NULL, 
[IsAnonymous] [bit] NOT NULL, 
[LastActivityDate] [datetime] NOT NULL, 
PRIMARY KEY NONCLUSTERED 
(
[UserId] ASC 
) 

我略去了外鍵,但本質上這歸結到:

  • 一個類可以有許多節。
  • 一節只能屬於一個班,但可以有很多學生。
  • 學生(aspnet_Users)可以屬於多個部分。

我已經設置了相應的模型類和流利NHibernate映射類,所有工作正常。

這裏是我卡住的地方。我需要編寫一個查詢,根據學生的UserId和班級日期返回學生註冊的章節。

這裏是我試過到目前爲止:

1.

var sections = (from s in this.Session.Linq<Sections>() 
where s.Class.StartDate <= DateTime.UtcNow 
&& s.Class.EndDate > DateTime.UtcNow 
&& s.Students.First(f => f.UserId == userId) != null 
select s); 

2.

var sections = (from s in this.Session.Linq<Sections>() 
where s.Class.StartDate <= DateTime.UtcNow 
&& s.Class.EndDate > DateTime.UtcNow 
&& s.Students.Where(w => w.UserId == userId).FirstOrDefault().Id == userId 
select s); 

顯然,上述2將,如果沒有學生匹配用戶ID來慘敗對它的開始和結束日期之間的當前日期進行分類......但我只是想嘗試。

類StartDate和EndDate的過濾器工作正常,但與學生的多對多關係證明是困難的。每次嘗試運行查詢時,都會收到帶有以下消息的ArgumentNullException:

值不能爲空。 參數名稱:session

我已經考慮過要使SectionStudents關係成爲Model類的引用Section和引用Student而不是多對多的路徑。如果可以的話,我想避免這種情況,而且我甚至不確定它會如此。

在此先感謝任何可以幫助的人。

瑞安

回答

0

對於任何人誰在乎,它看起來像下面的將來可能的工作,如果LINQ到NHibernate的可以支持子查詢(或者我可以完全關閉基地,這可能是對的限制這是使用LINQ到NHibernate的標準API):

var sections = (from s in session.Linq<Section>() 
where s.Class.StartDate <= DateTime.UtcNow 
&& s.Class.EndDate > DateTime.UtcNow 
&& s.Students.First(f => f.UserId == userId) != null 
select s); 

運行此查詢時,但是我目前收到下面的異常在LINQPad:

在crite不能使用子查詢ria 沒有投影。

所以暫時我把它分成了2個操作。首先獲得學生和相應的部分,然後按類別日期過濾。不幸的是,這導致了對數據庫的2個查詢,但它對我的目的應該沒問題。