不是在SQL中,而是在c#中使用实体框架:是否有一种简单的方法将源记录复制到另一个表?列定义是相同的,但是目标表没有索引、键或约束。我有这个代码,我有问题的一行被标记为:
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集合并将其保存到DB。在我沿着这条路写一个方法将记录从一个Auto实体复制到一个AutoArchive实体之前,我想我应该检查一下是否已经有一些很棒的甜蜜已经在里面了。
你知道是否有吗?
TIA
你可能想考虑使用一个存储过程来完成记录的存档,然后在你的c#代码中调用它,这是一种更干净更简单的方式,它还允许你避免所有数据的往返
这是我想到的解决方案:
// 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;
}
虽然很丑,但是很好用。(