[英]How to deliver and save the query result from an existing table into another new table
I am using entityframework codefirst for a new database and an existing database. 我正在使用entityframework codefirst用于新数据库和现有数据库。 Now I want to save the query result from table Products in Northwind to a new one named NewProducts which is in the NewProductContext. 现在,我想将查询结果从Northwind中的表Products保存到NewProductContext中名为NewProducts的新结果。 In this solution I created a class named NewProductContext, which I just used for creating an new database with two columns id and newname; 在这个解决方案中,我创建了一个名为NewProductContext的类,我刚用它来创建一个包含两列id和newname的新数据库;
static void Main(string[] args)
{
using (var db = new NorthwindContext())
{
{
Console.Write("Enter a name for a new Product: ");
var productname = Console.ReadLine();
var product = new Product { ProductName = productname };
db.Products.Add(product);
db.SaveChanges();
//LINQ query for the table
var query = from p in db.Products
//where p.ProductName.Contains("A")
orderby p.ProductName.Length
select p;
Console.WriteLine("All products in the database:");
foreach (var item in query)
{
Console.WriteLine(item.ProductName);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
/* using (var db1 = new NewProductContext())
{
foreach (var item in query)
{
var newpro = item;
db.NewProducts.Add(item)
db.Savechanges();
}
}*/
The method in comments is just my thinking, I know that there are many errors. 评论中的方法只是我的想法,我知道有很多错误。 But can anybody provide a new method to save the query result? 但任何人都可以提供一种新方法来保存查询结果吗? I created the database by this code 我通过这段代码创建了数据库
namespace CodeFirstExistingDatabaseSample
{
public class NewProduct
{
public int NewProductID { get; set; }
public string NewProductName { get; set; }
}
public class NewProductContext : DbContext
{
public DbSet<NewProduct> NewProducts { get; set; }
}
}
How about plain sql ? 普通sql怎么样? something like that 类似的东西
INSERT INTO targetDatabase.new_products (id,newname)
(SELECT id, name FROM sourceDatabase.products);
Of course the two databases must be on the same server 当然,这两个数据库必须位于同一台服务器上
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.