0

我是一名新的 ASP.NET 开发人员,我有 2 个输入形式为 DateTimes;开始日期和结束日期。我想确保它们都在另一个表的父级的 StartDate 和 EndDate 内。逻辑应该如下:

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

那么我该怎么做这个逻辑呢?

供您参考,我在数据库中有两个表,即;客户和项目。他们的架构是: 客户表:

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#1 和 EndDate#1。在客户表中,我有 StartDate#2 和 EndDate#2。逻辑应该执行以下操作:

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

0 回答 0