实体框架 - SaveOrUpdate最佳实践

时间:2014-06-02 02:47:19

标签: entity-framework unit-of-work

我一直在为我的项目使用Entity Framework 6和Ninject。我使用Ninject将数据库上下文注入到一个名为UserService的类中,该类下面有一个方法,检查用户及其相关产品是否存在,如果确实存在则执行更新,如果它没有添加到数据库中。

以下是代码:

   public void SaveOrUpdateUserProduct(int userId, int productId)
    {
        if (!this._db.UserProducts.Any(p => p.UserId.Equals(userId) && p.ProductId.Equals(productId)))
        {
            UserProduct uproduct = new UserProduct();
            uproduct.ProductId = productId;
            uproduct.DateUpdated = DateTime.Now;
            uproduct.ViewCount = 1;
            uproduct.UserId = userId;
            this._db.UserProducts.Add(uproduct);
            this._db.SaveChanges();
        }
        else
        {
            // Record already exists so lets just update it.
            UserProduct existingUserProduct = this.GetUserProduct(userId, productId);
            existingUserProduct.ViewCount = existingUserProduct.ViewCount + 1;
            existingUserProduct.DateUpdated = DateTime.Now;
            this._db.SaveChanges();
        }
    }

但是,我偶尔会收到以下错误:

System.Data.SqlClient.SqlException:无法在对象' dbo.UserProducts'中插入重复的键行。具有唯一索引' IX_UserProducts'。重复键值为(1218,2264)。声明已经终止。

告诉我,当上述代码块仍在执行时,必须在某个时刻添加userid / productid。

关于如何最好地减轻这种情况的一些建议?

0 个答案:

没有答案