克隆或复制同一表中的行

时间:2012-04-08 18:52:28

标签: linq-to-sql

我正在使用LINQ to SQL,我有一个名为“tblCourse”的表我想根据某些条件从该表中选择一些行,然后将这些选定的行作为新记录插入到同一个表中。任何机构都可以建议一些帖子,链接或方向吗?

public IQueryable<tblCourseNeededHours> CloneAllCourseNeededHoursInDepartmentInSemester(int departmentId, string semester)
{
return from allCourses in _db.tblCourseNeededHours orderby allCourses.tblCourse.CourseName
where allCourses.tblCourse.tblInstitute.DepartmentID == departmentId && allCourses.Semester
== semester select allCourses;

var thisTable = from t in _db.tblCourseNeededHours where
t.tblCourse.tblInstitute.DepartmentID == departmentId && t.Semester == semester

//select everything except ID
select _db.tblCourseNeededHours {  Semester = ?, NeedHoursPerWeek = ?, AssignToInstitute=? 
(I want it null for new record), Freezed=? (I want it null for new record)    
}; 
_db.tblCourseNeededHours.InsertAllOnsubmit(thisTable);
_db.SubmitChanges(); 

现在我使用

select _db.tblCourseNeededHours {  Semester = ?, NeedHoursPerWeek = ?, AssignToInstitute=? (I want it null), Freezed=? (I want it null)    
};

?提到“我应​​该放在这里,我在这里有错误,也在这一行

_db.tblCourseNeededHours.InsertAllOnsubmit(thisTable);

1 个答案:

答案 0 :(得分:0)

我不确定你的数据库模式,但是这样的事情对你有用。

var oldItems= (from p on db.tblCourses where p.InstructorId=43 select p).ToList();
if(oldItems!=null)
{
  foreach(var item in oldItems)
  {
    tblCourse objNew=new tblCourse();
    objNew.Instructor="John";  
   // update someproperty values from old row if you need        
    objNew.Credits=item.Credits+2;
    db.tblCourses.Add(objNew);
  }
  db.SubmitChanges();
}

假设db是你的datacontext