我有两个相同的sql表:dbo.Smith_Products和temp.Smith_Products。
我在不同的命名空间下有两个相同的类:IMS.Model.dbo和IMS.Model.temp
我正在尝试使用Mapper将数据从一个表移动到另一个表:
var spc = new Smith_ProductsController();
// get all Smith_Products records
spc.Gets();
// our temp.Smith_Products entity -- exact same table definition, exact same class definition. Different sql schema, different namespace
var spctemp = new imstemp.Smith_ProductsController();
// config and initialize our mapper
var config = new MapperConfiguration(cfg => cfg.CreateMap<Smith_Products, imstemp.Smith_Products>());
var mapper = config.CreateMapper();
// copy from dbo recordset to temp recordset
spctemp.Recordset = mapper.Map<Smith_Products[], IList<imstemp.Smith_Products>>(spc.Recordset.ToArray());
spctemp.Repository.DataSet.Create();
spctemp.Repository.DataSet.AddOrUpdate(spctemp.Recordset.ToArray());
var x = spctemp.Repository.SaveChanges();
// on first run with an empty temp.Smith_Products table, this works fine. Inserts 114 records
// on subsequent runs, x should = 0 because we've not changed or added anything
// however, this is not the case. Second run=108, 3rd run=34, etc. Records are being duplicated excecpt for ProductID, our key (identity,increment)
// then we do this each time
// retrieve the temp.Smith_Product records
spctemp.Gets();
// Change nothing
spctemp.Repository.DataSet.AddOrUpdate(spctemp.Recordset.ToArray());
// x should equal 0 each time
x = spctemp.Repository.SaveChanges();
//and it does.
Repository类只是我的控制器的子类:
public class RepositoryContext : DbContext
{
public DbSet<Smith_Products> DataSet { get; set; }
public RepositoryContext()
{
Database.Connection.ConnectionString = "xxx"
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Smith_Products>().ToTable("dbo.Smith_Products");
}
}
public RepositoryContext Repository=new RepositoryContext();
我的问题是,当这些记录不应该插入时,添加重复记录会发生什么?映射器是否未正确转换?
谢谢, 克里斯
答案 0 :(得分:0)
我想通了。
ProductID不一定在两个表之间匹配。当我将原始表复制到临时模式时,我没有将Identity种子设置为429,即原始表中的下一个递增键。
想出来,瞧,一切都是洁净的。
克里斯