Jawad
Jawad

Reputation: 70

Copy or clone rows from SQL Server table

Here is my code after modifications, things seems working fine but I am receiving an error on _db.SubmitChanges();

Error is

Cannot add an entity with a key that is already in use.

Code:

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();

I am using MVC 2.0 and SQL Server. I have a table called tblCourses.

I want to select rows based on some selection criteria, then I want to append these rows to tblCourse.

Do I need to create a temporary table tmpCourse and to fill in these selected rows and then append them those back to tblCourse? Or can I do it without temporary table?

Any suggestion, post link ?

Upvotes: 0

Views: 1325

Answers (1)

marc_s
marc_s

Reputation: 754478

I believe you can just do something like:

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

Of course, the list of columns must match, e.g. you have to have the same number of columns, and the same datatypes. Also, you cannot insert values into e.g. IDENTITY or computed columns.

Update: to do this in Linq-to-SQL, you'd have to have an entity that can represent your data in some way. Then:

  • select the data from your existing database into a List<Entity> (or whatever your entity is really called)
  • create new objects (entities) based on those retrieved - change your properties as needed
  • insert those entities back into the data context
  • save the changes.

Something along the lines of this code snippet (here I have a table countries which has an ISOCode and a CountryName for some countries; I'm selecting a few, and creating new ones based on those retrieved, adding those new ones to the Linq-to-SQL DataContext and saving in the end):

// 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();
}

Upvotes: 3

Related Questions