3

親オブジェクトへの外部キーであるエンティティを保存しようとすると問題が発生します..

私は amazonProduct エンティティを持っています。そして、次のような amazonProduct の仮想リストである AmazonCompetitivePrice エンティティ:

public class AmazonProduct
{
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public virtual int ASIN

        public virtual IList<AmazonProductCompetitivePrice> amazonProductCompetitivePrices = new List<AmazonProductCompetitivePrice>();
}

したがって、データベースから取得した AmazonProduct があり、新しい AmazonProductCompetitivePrice を amazonProduct に追加します。

しかし、これを保存しようとすると、次のエラーが発生します。

PRIMARY KEY 制約「PK_dbo.AmazonProducts」に違反しています。オブジェクト 'dbo.AmazonProducts' に重複するキーを挿入できません。\r\nステートメントは終了しました

私の AmazonProduct が既にデータベースにあることを認識していないようで、新しいものを保存しようとしていますが、主キーは既に存在しています!

流暢な API を使用して、次のように外部キーをマップしました。

        modelBuilder.Entity<AmazonProduct>()
                    .HasMany(pl => pl.AmazonProductCompetitivePrices)
                    .WithOptional(p => p.AmazonProduct)
                    .Map(c => c.MapKey("ASIN"));

誰がこれの何が悪いのか知っていますか?

前もって感謝します!

編集: オブジェクトの取得:

 using (var uow = new UnitOfWorkInventory())
            {
                using (var amazRepo = new AmazonProductRepository(uow))
                {
                    return amazRepo.FindByAsin(ASIN);
                }
            }
 public AmazonProduct FindByAsin(string asin)
        {
            return context.AmazonProducts.Include(x => x.AmazonLowestOfferListings).Include(x => x.AmazonMyPrices).Include(x => x.AmazonProductCompetitivePrices).SingleOrDefault(x => x.ASIN == asin);
        }

それは私にAmazonProductを取得します..次に保存します:

using (var uow = new UnitOfWorkInventory())
{
     using (var amazonRepo = new AmazonProductCompetitivePriceRepository(uow))
     {
          amazonProductCompetitivePrice.AmazonProduct = amazonProduct;
          amazonRepo.InsertOrUpdate(amazonProductCompetitivePrice);
     }
          uow.Commit();
}

  public void InsertOrUpdate(AmazonProductCompetitivePrice amazonProductCompetitivePrice)
    {
        if (amazonProductCompetitivePrice.Id == default(int))
        {
            // New entity
            context.AmazonProductCompetitivePrices.Add(amazonProductCompetitivePrice);
        }
        else
        {
            // Existing entity
            context.Entry(amazonProductCompetitivePrice).State = EntityState.Modified;
        }
    }

それがすべて..そして助けてくれてありがとう!!

4

2 に答える 2

0

最初にこの問題がありました 削除しました

[DatabaseGenerated(DatabaseGeneratedOption.None)]

私のエンティティクラスからの注釈。次に、SQL サーバーから手動でテーブルを削除し、 パッケージ マネージャー コンソールで再度使用update-database -Verbose しました。NuGet今、それは動作します!

于 2015-12-08T09:10:25.790 に答える