使用EF / LINQ将记录从一个表复制到另一个表(存档记录)

时间:2011-04-16 00:23:52

标签: linq entity-framework

不在SQL中但在C#中使用Entity Framework:是否有一种简单的方法将源记录复制到另一个表?列定义相同,但目标表没有索引,键或约束。我有这个代码,我遇到问题的那一行标有:

private void HandleAutos()
{
    // convert to List<auto>...
    List<Model.Auto> imports = ConvertAuto();

    // get all DB records in List<auto>...
    List<Model.Auto> current = _dbFeed.Autoes.Where(a => a.ClientID == _targetClientID && a.Active == true).ToList();

    // isolate all Inserts, Updates and Deletes...
    var existing = imports.Intersect(current, new AutoIsIn()).ToList();         // should be all autos with matching VIN & SKU  //
    var updates = existing.Intersect(current, new AutoHasChanged()).ToList();   // should be a subset of changed resords        //
    var inserts = imports.Except(current, new AutoIsIn()).ToList();             // should be all the imports not in the DB      //
    var deletes = current.Except(imports, new AutoIsIn()).ToList();             // should be all the DB records not in imports  //

    // THIS IS THE BAD LINE //
    deletes.ForEach(a => _dbFeed.AddToAutoArchives(a));  // <=======
    // -------------------- //
    deletes.ForEach(a => _dbFeed.DeleteObject(a));
    updates.ForEach(a => _dbFeed.ApplyCurrentValues("Autoes", a));
    inserts.ForEach(a => _dbFeed.AddToAutoes(a));

    _dbFeed.SaveChanges();
}

我知道我可以遍历我的源记录,创建存档记录,复制每个属性,最后将新实体添加到ArchiveAutos集合并将其保存到数据库。在我沿着那条路走下去并写了一个方法来将记录从Auto实体复制到AutoArchive实体之前,我会检查是否已经有一些令人敬畏的甜蜜了。

你知道是否有?

TIA

2 个答案:

答案 0 :(得分:0)

您可能需要考虑使用存储过程来完成记录的归档,只需从C#代码中调用它,这样就更清晰,更简单,也可以避免所有数据的往返

答案 1 :(得分:0)

以下是我提出的解决方案:

// Archive the records to be deleted...
if (_deletes.Count > 0)
{
    // ignore deletes less than 60 days old...
    var myDeletes = _deletes.Where(a => a.DateCreated <= DateTime.Now.AddDays(-60)).ToList();

    List<Model.AutoArchive> archiveList = ConvertAuto(myDeletes);
    archiveList.ForEach(a => _dbFeed.AutoArchives.Add(a));
    _dbFeed.SaveChanges();

    // Drop the records no longer in the feed...
    foreach (var d in myDeletes)
    {
        var myImages = _dbFeed.Images.Where(a => a.ParentRecordID == d.AutoID).ToList();
        myImages.ForEach(a => _dbFeed.Images.Remove(a));
    }
    myDeletes.ForEach(a => _dbFeed.Autoes.Remove(a));
    _dbFeed.SaveChanges();
}

private List<Model.AutoArchive> ConvertAuto(List<Model.Auto> deletes)
{
    List<Model.AutoArchive> aa = new List<Model.AutoArchive>();
    foreach (var a in deletes)
    {
        aa.Add(new Model.AutoArchive
        {
            ID = Guid.NewGuid(),
            Active = a.Active,
            ....
            ImageList = a.ImageList
        });
    }

    return aa;
}

丑陋但是有效。 :(