score:2
Consider using dbConext.ExecuteCommand()
function to execute SQL directly, e.g.:
ctx.ExecuteCommand("INSERT INTO backup SELECT * FROM original");
Alternatively you could use InsertAllOnSubmit, e.g.:
var entries = dbContextOldTables.AsEnumerable().Select(x => new NewTable() { /* mapping */ });
dbContext.NewTables.InsertAllOnSubmit(entries);
Edit 2010-04-09:
Passing an IQueryable
into InsertAllOnSubmit
that constructs a new item (i.e. new NewTable()
) fails for the following reason (source):
This check was added because it was supposed to be there from the beginning and was missing. Constructing entity instances manually as a projection pollutes the cache with potentially malformed objects, leading to confused programmers and lots of bug reports for us. In addition, it is ambiguous whether projected entities should be in the cache or changed tracked at all. The usage pattern for entities is that they are created outside of queries and inserted into tables via the DataContext and then later retrieved via queries, never created by queries.
So the error occurs because the IQueryable
is trying to create an item on the cache by executing and SQL query that returns the item specified by the select. Converting the IQueryable
into an IEnumberable
using the AsEnumerable()
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:
using (var ctx = new NorthwindDataContext()) {
var categories = ctx.Categories;
var catcopy = categories.Select(x => new CategoriesBackup() {
CategoryID = x.CategoryID,
CategoryName = x.CategoryName,
Description = x.Description,
Picture = x.Picture
});
//ctx.CategoriesBackups.InsertAllOnSubmit(catcopy); // THIS DOES NOT WORK
var catcopy2 = categories.AsEnumerable().Select(x => new CategoriesBackup() {
CategoryID = x.CategoryID,
CategoryName = x.CategoryName,
Description = x.Description,
Picture = x.Picture
});
ctx.CategoriesBackups.InsertAllOnSubmit(catcopy2); // THIS WORKS
}
score:1
You could use Automapper (http://automapper.codeplex.com/) or some very simple reflection code to copy the data from one object to the other so you don't need to manually write out each field.
For example, using an interface to ensure they match:-
public interface IShared
{
int Prop1 {get; set;}
string Prop2 {get; set;}
}
public class A : IShared
{
public int Prop1 {get; set;}
public string Prop2 {get; set;}
}
public class B : IShared
{
public int Prop1 {get; set;}
public string Prop2 {get; set;}
}
static void Main(string[] args)
{
A A = new A(){ Prop1 = 1, Prop2 = "2" };
B B = new B();
var properties = typeof(IShared).GetProperties();
foreach (var prop in properties)
{
object currentValue = prop.GetValue(A, null);
prop.SetValue(B, currentValue, null);
}
Console.WriteLine("B = " + B.Prop1 + " " + B.Prop2);
Console.ReadKey();
Note: This does NOT handle arrays, you could extend it to do that, or your could just use Automapper.
Source: stackoverflow.com
Related Query
- Mapping LINQ to SQL table to another very similar table without iterating through every one
- Updating table with new objects without mass delete through LINQ to SQL in C#
- Increase SQL Command Timeout when making call through LINQ Mapping
- How to remove selected data that found on another list and take last 6 id through LINQ without foreach loop
- SQLite DB: Create a SQL Statement with LINQ that uses the same table twice but without CROSS JOIN
- LINQ to SQL to find values starting with characters from another table
- how to insert data in 1 table and update another table in a sql database using linq
- Does Linq in Entity Framework code first use SQL or does it get the whole table first?
- c# linq to sql iterating through left join results
- Optimise and speed up very slow Linq / SQL code
- Linq query in ASP.net MVC accessing another table through a table
- How to update Linq result with in the list, without assign other data table process itself get another one result
- how to get a table data where should be checked in another table without joining using linq include or another way?
- Inner Join Two Datatable using Linq without having relation with another table
- generating sql script from linq through c# code
- How are people unit testing code that uses Linq to SQL
- Mapping a list of object models onto another list using linq
- Steps for a beginner to run very basic linq to sql query using Linqpad
- Convert LINQ Expression to SQL Text without DB Context
- LINQ to SQL Every Nth Row From Table
- Linq To SQL Without Explicit Foreign Key Relationships
- How to add field not mapped to table in Linq to Sql
- How to implement SkipWhile with Linq to Sql without first loading the whole list into memory?
- Deleting rows in a table with Linq to SQL
- Linq query join one table row to another table multiple row
- LINQ to SQL Association Mapping
- Is there any way to create a LINQ query as a variable without having the data source (yet)?
- Will indexing a SQL table improve the performance of a LINQ statement?
- Add Object Collection to another Object Collection without iterating
- Linq to Sql - Loading Child Entities Without Using DataLoadOptions?
More Query from same tag
- Linq add dynamic where clause
- LINQ to Entities does not recognize the method 'System.Object InjectFrom(System.Object, System.Object[])'
- Convert Dictionary<int, int?> to Dictionary<int, int> by skipping null values with LINQ
- Execute stored procedure using entity framework
- How to make 2 dictionary and group it twice
- How to get the distinct record name and its each record count to bind to gridview in C# using Linq from SQL Server
- Rotating table, LINQ syntax
- How to fully simulate the behavior of a SQL Like in Linq-to-Entities
- C#: Get the 5 newest (last modified) files from a directory
- Remove Last 30 Days Nodes from XML Document using linq
- How to use LINQ to group objects in two groups
- File Download MVC
- Why can't I use the enumerator of an array, instead of implementing it myself?
- Write stored procedures in Linq/Lambda (Unit-testable but performant stored procs). Possible?
- LINQ IEnumerable Where Not Finding Element
- Linq with Logic
- Linq - filter on multiple possible equals values
- Data sorting inside n-layered application
- How can I extend a field of a class?
- Searching for multiple strings using single database query with entity framework and LINQ
- Use LiNQ to see if a "value" exists from an array in c#
- Linq join object list with integer list
- LINQ query with Distinct and Union
- Linq relational table include
- Select by key from another list in LINQ
- Count does not return the right count properly
- Applying pagination on subcollection
- Slow LINQ query for .ToArray()
- Entity Framework and ObservableCollections
- LINQ Comparing Two Lists - Add new, remove old, leave the ones in common