0
dbo.Smith_Productsとtemp.Smith_Productsの2つの同一のSQLテーブルがあります。DbContextとDbSetを使用すると予期しない動作が発生する
私は、異なる名前空間の下に二つの同一のクラスを持っている:
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.
:IMS.Model.dboとIMS.Model.temp
私はマッパーを使用して別のテーブルからデータを移動しようとしていますリポジトリクラスは、単に私のコントローラのサブクラスである:
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();
私の質問は、それらのレコードを持っていなければならないとき、重複レコードの追加で何が起こっているか、です挿入されましたか?マッパーは正しく変換されていませんか?
おかげで、 クリス
これは、2つのテーブル間でデータをコピーするのに非常に非効率的な方法です。 SQLを直接書いていない理由はありますか? – Dai
それは信じられないほど非効率です。ありがとうございました。それはここの運動の目的ではありませんでした。その目的は、AddorUpdateまたは "upsert"を使用してテーブル上でDbSetトランザクションを実行すると、データが壊れないようにすることでした。 問題が見つかりました。それは必ずしも1つではありませんでした。しかし、あなたのコメントに感謝します。ここにあなたのSQLコードです: は、既存のデータから新しいテーブルを作成: はsmith_products または からtemp.smith_productsに選択* smith_productsから選択temp.smith_products *に挿入します。 identity_insertがオンになっていることを確認してください。 あなたが探していたものですか? – Chris