Link to home
Start Free TrialLog in
Avatar of dkilby
dkilbyFlag for Canada

asked on

Linq To SQL + Move Data From One Table To Another

I would like to move a row of data from one table(tableA) to another table (tableB) and then once it is moved delete the row from tableA

I would like to use Linq To SQL if possible.

Is this possible and if so how ?

Thanks
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Hi dkilby;

Yes it can be done. But first of all Microsoft's recommendations for new projects is to use Linq to Entity Framework and not Linq to SQL. The reason for this is that that are not adding new features to Linq to SQL and only doing bug fixes. Using Linq to Entity Framework it can be done as follows
// Create the DbContext object.
TheDbContextEntities db = new TheDbContextEntities();
// Find the record to be deleted from TableA by using a query like the following
var employee = db.TableAs.Where(emp => emp.Name == "Joe").FirstOrDefault();
// Because the above record is of type TableA you will need to copy the fields from it
// to a record of type TableB. Note in this new record I did not copy the Primary key
// this will be added by TableB when inserted.
TableB moveEmployee = new TableB { Name = employee.Name, Age = employee.Age, ... };
// Add the new record to TableB 
db.TableBs.Add(moveEmployee);
// Delete the record from TableA
db.TableAs.Remove(employee);
// Save the changes.
db.SaveChanges();

Open in new window

Avatar of dkilby

ASKER

Thank you for the info regarding Linq To SQL, will keep that in mind for any new projects.

I would like for this project to finish it off using Linq To SQL - is it possible to make the movement of a row with Linq To SQL ?
Are the two tables, TableA and TableB, have the exact same schema?
Avatar of dkilby

ASKER

yes both tables have the same schema
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dkilby

ASKER

Great, worked perfect thank you very much
Not a problem dkilby, glad I was able to help.