如何检查项目的日期时间是否在其他两个日期的范围内?

时间:2013-10-12 17:50:26

标签: c# asp.net sql linq-to-entities

我是一名新的ASP.NET开发人员,我在表单中有2个输入作为DateTimes; StartDate和EndDate。我想确保它们都在另一个表的Parent的StartDate和EndDate中。逻辑应该如下:

  1. 检查项目的StartDate是否在EndDate之前。
  2. 检查StartDate&插入项的EndDate在Customers表
  3. 中的StartDate和EndDate的范围内

    那我怎么做这个逻辑?

    为了您的信息,我在数据库中有两个表,即;客户和Items.Their架构是: 客户表:

    CREATE TABLE [dbo].[Customers](
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [Name] [varchar](50) NULL,
        [Job] [varchar](50) NULL,
        [StartDate] [datetime] NOT NULL,
        [EndDate] [datetime] NOT NULL,
     CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED 
    (
        [ID] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    

    项目表:

    CREATE TABLE [dbo].[Items](
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [Name] [varchar](50) NOT NULL,
        [Description] [varchar](50) NULL,
        [StartDate] [datetime] NOT NULL,
        [EndDate] [datetime] NOT NULL,
        [CustomerID] [int] NOT NULL,
     CONSTRAINT [PK_Items] PRIMARY KEY CLUSTERED 
    (
        [ID] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    
    SET ANSI_PADDING OFF
    GO
    
    ALTER TABLE [dbo].[Items]  WITH CHECK ADD  CONSTRAINT [FK_Items_Customers] FOREIGN KEY([CustomerID])
    REFERENCES [dbo].[Customers] ([ID])
    GO
    
    ALTER TABLE [dbo].[Items] CHECK CONSTRAINT [FK_Items_Customers]
    GO
    

    我的C#代码:

    protected void btnSubmit_Click(object sender, EventArgs e)
        {
            DateTime startDate = Convert.ToDateTime(txtStartDate.Text);
            DateTime endDate = Convert.ToDateTime(txtEndDate.Text);
            if (DateTime.Compare(startDate, endDate) <= 0)
            {
                using (TestDBEntities1 TEntities = new TestDBEntities1())
                {
                    var newItem = new Item
                    {
                        Name = txtName.Text,
                        Description = txtDesc.Text,
                        StartDate = startDate,
                        EndDate = endDate,
                        CustomerID = Convert.ToInt32(ComboBox1.SelectedValue)
                    };
                    TEntities.Items.AddObject(newItem);
                    TEntities.SaveChanges();
                }
                lblMessage.Text = "Successfully Added :)";
            }
            else
            {
                lblMessage.Text = "Error!!!";
            }
        }
    

    注意:我正在使用LINQ来查询数据库。我只是错过了检查StartDate&amp; amp;插入项的EndDate位于Customers表的日期内。

    解释

    例如,假设我们有一个将要插入的项目的StartDate#1和EndDate#1。在Customers表中,我有StartDate#2和EndDate#2。逻辑应该执行以下操作:

    1. 检查StartDate#1是否在EndDate#1
    2. 之前
    3. 然后,检查StartDate#1和EndDate#1是否属于StartDate#2和EndDate#2的范围

0 个答案:

没有答案