2012-04-08 136 views
0

這裏是我的代碼修改後,事情似乎工作正常,但我對_db.SubmitChanges();從SQL Server表複製或克隆行

錯誤接收錯誤

不能一鍵添加一個實體已在使用中。

代碼:

foreach (tblCourseNeededHours record in thisTable) 
{ 
      tblCourseNeededHours newCNHR = new tblCourseNeededHours(); 
      newCNHR.Semester = a_semesterToOrganize; 
      newCNHR.AssignToInstituteAdministrator = false; 
      newCNHR.Freezed = false; 

      _db.tblCourseNeededHours.InsertOnSubmit(newCNHR); 
} 

// submit all the changes 
_db.SubmitChanges(); 

我使用MVC 2.0和SQL Server。我有一張名爲tblCourses的表格。

我想根據一些選擇標準選擇行,然後我想將這些行追加到tblCourse

我需要創建一個臨時表tmpCourse並填寫這些選定的行,然後將它們追加到tblCourse?或者我可以不用臨時桌子嗎?

任何建議,張貼鏈接?

回答

3

我相信你可以這樣做:

INSERT INTO dbo.tblCourse(list of columns) 
    SELECT (list of columns) 
    FROM dbo.tblCourse 
    WHERE (your condition here.....) 

當然,列的列表必須匹配,例如你必須有相同數量的列和相同的數據類型。另外,您不能將值插入IDENTITY或計算列。

更新:要在Linq-to-SQL中執行此操作,您必須擁有可以某種方式表示數據的實體。然後:

  • 選擇從現有的數據庫中的數據爲List<Entity>(或任何你的實體真的叫)
  • 創建新的對象基於這些檢索(實體) - 改變你的屬性需要
  • 插入那些實體回到數據上下文
  • 保存更改。我選擇了幾下,並創建基於這些檢索到的新的,增加的;

沿此代碼段的線(在這裏我有有ISOCode和一些國家CountryNamecountries東西新的LINQ到SQL DataContext,並最終節省):

// create and use the Linq-to-SQL DataContext 
using (LinqSampleDataContext ctx = new LinqSampleDataContext()) 
{ 
    // select some data 
    IQueryable<country> existingCountries = ctx.countries.Where(c => c.CountryID < 100); 

    // loop over selected data - create new entities based on data retrieved 
    foreach (country c in existingCountries) 
    { 
     country newCountry = new country(); 
     newCountry.CountryName = c.CountryName; 
     newCountry.ISOCode = "X" + c.ISOCode.Substring(1); 

     // add new entities to DataContext 
     ctx.countries.InsertOnSubmit(newCountry); 
    } 

    // submit all the changes 
    ctx.SubmitChanges(); 
} 
+0

我使用LINQ to SQL,有人可以幫我上面提到的查詢中的LINQ to SQL翻譯。在這種情況下,我在初學者水平 – Jawad 2012-04-08 18:49:07

+1

@Jawad:用Linq-to-SQL示例更新了我的回覆 – 2012-04-08 19:04:37

+0

請檢查更新代碼,我在代碼的最後一行收到錯誤,錯誤爲「無法添加實體與一個已經在使用的密鑰「。 – Jawad 2012-04-09 15:00:01