我写了一个非常简单的方法。它将类DayWeather
中的数据保存到数据库中。方法检查表中是否存在当天的行并更新她或创建新行。
我通过为 LINQ 添加新类并将表从 Server Inspector 移动到构造函数来做到这一点。它生成新类WeatherTBL
。
方法本身如下所示:
public static void SaveDayWeather(DayWeather day)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var existingDay =
(from d in db.WeatherTBL
where d.DateTime.ToString() == day.Date.ToString()
select d).SingleOrDefault<WeatherTBL>();
if (existingDay != null)
{
existingDay.Temp = day.Temp;
existingDay.WindSpeed = day.WindSpeed;
existingDay.Pressure = day.Pressure;
existingDay.Humidity = day.Humidity;
existingDay.Cloudiness = day.Cloudiness;
existingDay.TypeRecip = day.TypeRecip;
db.SubmitChanges();
}
else
{
WeatherTBL newDay = new WeatherTBL();
newDay.DateTime = day.Date;
newDay.Temp = day.Temp;
newDay.WindSpeed = day.WindSpeed;
newDay.Pressure = day.Pressure;
newDay.Humidity = day.Humidity;
newDay.Cloudiness = day.Cloudiness;
newDay.TypeRecip = day.TypeRecip;
db.WeatherTBL.InsertOnSubmit(newDay);
db.SubmitChanges();
}
}
}
当我试图从 UnitTest 项目中给他打电话时:
[TestMethod]
public void TestDataAccess()
{
DayWeather day = new DayWeather(DateTime.Now);
DataAccessClass.SaveDayWeather(day);
}
它写道,该测试已成功通过。但是如果查看表格,它并没有改变。没有错误信息显示。有谁知道是什么问题?
PS对不起我的英语不好。
UDP 问题在于:“...db 可能会在每次构建时复制到调试或发布文件夹,覆盖您修改过的文件夹”。谢谢@Silvermind