Apologies for the vague question. Here it is: I have a table object created by LINQ to SQL. I am copying entries from one table to an “archive” table that has all the columns of the original, plus a couple extra ones.
It feels sloppy to iterate through every object and manually define the mapping like:
foreach (oldTable in dbContextOldTables)
{
var newTable = new NewTable();
newTable.TableID = oldTable.ID;
newTable.Title = oldTable.Title;
... (repeat for twenty columns)
newTable.ColumnThatIsntInOldTable = "Data that will be the same for every row";
dbContext.NewTables.InsertOnSubmit(newTable);
}
dbContext.SubmitChanges();
Is there a clever way to do this?
Consider using
dbConext.ExecuteCommand()function to execute SQL directly, e.g.:Alternatively you could use InsertAllOnSubmit, e.g.:
Edit 2010-04-09:
Passing an
IQueryableintoInsertAllOnSubmitthat constructs a new item (i.e.new NewTable()) fails for the following reason (source):So the error occurs because the
IQueryableis trying to create an item on the cache by executing and SQL query that returns the item specified by the select. Converting theIQueryableinto anIEnumberableusing theAsEnumerable()function breaks the SQL generation. So the query generated just selects the item (i.e. the SQL does not do the mapping) and the construction of the new item is done outside the Linq to SQL logic.To be sure I tested the approach using a Northwind DB in which I created a copy of the Categories table using the code below: