2013-05-05 58 views
0

我寫了一個非常簡單的方法。它將數據從類DayWeather保存到數據庫。方法檢查表中是否存在與當天的行,並更新她或創建一個新行。使用LINQ將數據插入數據庫

我通過爲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(); 
      } 
     } 
    } 

當我試圖給他打電話從單元測試項目:

[TestMethod] 
    public void TestDataAccess() 
    { 
     DayWeather day = new DayWeather(DateTime.Now); 
     DataAccessClass.SaveDayWeather(day); 
    } 

寫,該測試已順利通過。但如果看一下桌子,它就沒有cha。。 沒有顯示錯誤消息。有誰知道最新的問題?

P.S.對不起,我的英語不好。

UDP 問題在於: 「......分貝可能複製到調試或在每次構建發佈文件夾,覆蓋你修改的一個」。謝謝@Silvermind

+0

我不知道爲什麼它不存儲數據。但是你的單元測試只是調用方法,而不是使用assert來驗證結果。 – 2013-05-05 19:21:06

+0

@ARS,他沒有驗證結果。方法返回void。我檢查結果到表... – Advers191 2013-05-05 19:30:56

+0

我明白了。您仍然可以編寫一個方法來檢索數據並執行斷言。無論如何,這是一個不同的討論話題。你可以檢查連接字符串是否將數據插入到合適的分貝。 – 2013-05-05 19:39:39

回答

3

我寫了一個簡單的方法將員工詳細信息保存到數據庫中。

Checkout this link to know Insert, Update, Delete operations using LINQ C#

 private void AddNewEmployee() 
    { 
     using (DataContext objDataContext = new DataContext()) 
     {     
      Employee objEmp = new Employee(); 
      // fields to be insert 
      objEmp.EmployeeName = "John"; 
      objEmp.EmployeeAge = 21; 
      objEmp.EmployeeDesc = "Designer"; 
      objEmp.EmployeeAddress = "Northampton";     
      objDataContext.Employees.InsertOnSubmit(objEmp); 
      // executes the commands to implement the changes to the database 
      objDataContext.SubmitChanges(); 
     } 
     } 

Getting started with LINQ C#

0

請lambda表達式嘗試。在你的代碼,VAR existingDay類型的IQueryable 的爲了插入或更新,你需要WeatherTBL類型的變量變種existingDay。 因此嘗試使用下面..

var existingDay = 
db.WeatherTBL.SingleOrDefault(d => d.DateTime.Equals(day.Date.ToString())); 

if(existingDay != null) 
    { 
    //so on... 
    } 

希望它應該工作..