LINQ为两个表,其中日期范围在两个值之间

时间:2014-06-06 13:38:10

标签: linq c#-3.0

感谢我在LIQ中提供正确语法的问题,以获取ITEM表中未在ITEMRESERVED表中为日期范围保留的项目。

For Example: Item contain:
ItemID   ItemName
1        A
2        B
3        C


ItemReserved Contains:
ID     ItemID    StartDate   EndDate
1      1         06/06/14    07/06/14

表定义:

CREATE TABLE [dbo].[Item](
[ItemID] [int] NOT NULL,
[ItemName] [varchar](8) NOT NULL,

PRIMARY KEY CLUSTERED 
(
[ItemID] ASC
)

CREATE TABLE [dbo].[ItemReserved](
[ID] [int] NOT NULL,
[ItemID] [int] NOT NULL,
[StartDate] [smalldatetime] NOT NULL,
[EndDate] [smalldatetime] NOT NULL,

PRIMARY KEY CLUSTERED 
(
[ID] ASC
)

[FK_ItemReserved] FOREIGN KEY([ItemID])
REFERENCES [dbo].[Items] ([ItemID])

基于以下搜索详情:

选择ITEM表格中的所有项目,而不是在06-06-14&之间保留。 14年7月6日

到目前为止

代码:

var StartDate = DateTime.Now;
var EndDate = DateTime.Now.AddDays(1);

var query = from i in db.Ttem
            join ir in db.ItemReserved
            //on i.ItemID equals ir.ItemId - This line brings back the data that is reserved
            on i.ItemID (??? != ) ir.ItemId
            where i.ItemID == ir.ItemID //&& (Dates <= Start and >= End)
            select i;

此代码适用于选择为日期保留的内容,但不是我需要相反的内容,有什么不保留?

 var StartDate = dpStartDate.SelectedDate.Value;
 var EndDate = dpEndDate.SelectedDate.Value;

 //LINQ - To get all cars from database
 var query = from i in db.Item
             join ir in db.ItemReserved
             on i.ItemID equals ir.ItemID
             where i.ItemID == ir.ItemID && ((StartDate >= b.StartDate) && (EndDate <= b.EndDate))
             select i;

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

// Declaration of start and end date.
var StartDate = DateTime.Now;
var EndDate = DateTime.Now.AddDays(1);

// Get the items in db.Ttem that are reserved in the time period
// between StartDate and EndDate.
var query = from i in db.Ttem
            join ir in db.ItemReserved
            on i.ItemID equals ir.ItemId 
            where ir.StarDate >= Start && ir.EndDate<= End
            select i.ItemID;

// Get the items in db.Ttem that are not reserved in the time period
// between StartDate and EndDate.
var result = db.Ttem.Where(x=>!query.Contains(x));