【问题标题】:How to deliver and save the query result from an existing table into another new table如何将现有表中的查询结果传递并保存到另一个新表中
【发布时间】:2013-07-26 09:29:09
【问题描述】:

我将 entityframework codefirst 用于新数据库和现有数据库。现在,我想将 Northwind 表 Products 中的查询结果保存到 NewProductContext 中名为 NewProducts 的新表中。 在这个解决方案中,我创建了一个名为 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();
            }
        }*/

cmets中的方法只是我的想法,我知道有很多错误。但是任何人都可以提供一种新的方法来保存查询结果吗? 我通过这段代码创建了数据库

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; }
    }
}

【问题讨论】:

  • 那么您有两张表,EF 为您创建了这两张表,并且您想将其中一张的内容复制到另一张中?我说的对吗?
  • 据我所知,您必须像在代码中一样将它们一一复制。无法批量插入。
  • 你的 NewProductContext() 映射到什么类?例如,通常在上下文中,您具有 DbSet. 的属性
  • @Onam 嗨,一张表来自北风,我使用现有数据库的 ef 来创建模型,只是我自己创建了新的。 _namespace CodeFirstExistingDatabaseSample { public class NewProduct { public int NewProductID { get;放; } 公共字符串 NewProductName { 获取;放; } } 公共类 NewProductContext : DbContext { public DbSet NewProducts { get;放; } } } _这是我为要映射到的新表创建的代码。
  • @Onam 我在原始问题处编辑了代码,希望我能帮助您理解我的问题并在以后帮助我:)

标签: c# database entity-framework


【解决方案1】:

普通的 sql 怎么样? 类似的东西

INSERT INTO targetDatabase.new_products (id,newname) 
(SELECT id, name FROM sourceDatabase.products);

当然这两个数据库必须在同一台服务器上

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 2020-11-30
    • 2014-05-06
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多