Wpf C#DateTime数据库

我的数据库中有两个表,energyinfo(t1)和enerfyinfometers(t2).

我在t1有一个开始和停止时间,比如500分钟差异.

我想在t2中每隔一分钟在t1(开始和停止)之间添加时间.

这是我的代码.它需要花费大量的时间来运行并且t1条目正在发生但是没有做到t2.

if (dbContext == null)
{
    dbContext = Context.Create("d:\\temp\\new.sdf", "");

    var start = DateTime.Now;
    DateTime time = DateTime.Now;
    DateTime time2 = DateTime.Now;

    // time = time + TimeSpan.FromMinutes(30);
    time2 = time2 + TimeSpan.FromMinutes(1);

    Random rnd = new Random();
    double Counter = 50;
    var stop = start.AddMinutes(15);

    double value2 =36;

    for (int i = 1; i < 36; i++)
    {
        Counter = Counter + 0.5; 
        double value3 = rnd.Next (2,12) +0.5;
        double value4 = value3 / 2;
        double value = rnd.Next(50) +  0.5;

        value2 += (value / 60);
        double roundedValue = Math.Ceiling(value2) + 1;
        int LMH = rnd.Next(0, 3);

        dbContext.EnergyInfo.Add(new EnergyInfo() 
                                     { EId = i, 
                                       Timestamp = time, type = LMH, 
                                       startTime = start, stopTime = stop, 
                                       demandCharge = value3, 
                                       threshHold = 70, 
                                       normalCharge = value4, 
                                       peakDuration = 900 });

        dbContext.SaveChanges();

        for (var x = start; x < stop; x.AddMinutes(1))
        {
            var ob = new EnergyMeterInfo() { Timestamp = x, MeterId = 5, 
                                             powerConsumptionKW = Counter, 
                                             cumlativePwrConsumption = roundedValue, 
                                             EnergyInfoId = i };

            using (dbContext.Database.BeginTransaction())
            {
                dbContext.EnergyMeterInfo.Add(ob);
            }
        }

        start = stop;
        stop = start.AddMinutes(500);

        dbContext.SaveChanges();
    }
}

MessageBox.Show(dbContext.EnergyInfo.Count() + " Records found !" + dbContext.EnergyMeterInfo.Count() + " found");

最佳答案 x.AddMinutes(1)不会更改x的值.相反,它返回一个新的DateTime实例,然后您应该将其分配给x.

因此循环应如下所示:

for (var x = start; x < stop; x = x.AddMinutes(1))
{
    ...
}
点赞