在实体框架中复制表

时间:2019-08-16 09:49:05

标签: entity-framework asp.net-core

使用.NET Core 2.2和Entity Framework,将数据库表复制到新数据库表的最简单方法是什么。

即创建该表的存档副本。

2 个答案:

答案 0 :(得分:1)

我建议在EntityFrameworkCore中使用原始sql来完成所需的操作。

    dbContext.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, 
    "INSERT INTO TABLE2
    SELECT * FROM TABLE1" ); 

答案 1 :(得分:0)

如果内存不是问题

var sourceFiles = _context.SourceTables.ToList();

foreach(var sourceFile in sourceFiles)
{
    //if matching entity
    _context.DestinationTables.Add(sourceFile);
    //if not matching
    var destination = new DestinationEntity 
    {
        Prop1 = sourceFile.Prop1,
        //other properties
    }
    _context.DestinationTables.Add(destination);


    //if need to remove
    _context.SourceTables.Remove(sourceFile);
}

_context.SaveChanges();