【问题标题】:nopCommerce inserting entity failnopCommerce 插入实体失败
【发布时间】:2012-09-16 20:43:04
【问题描述】:

我正在为类别创建从 XML 函数导入。 首先,使用 XDocument,我创建了要添加的类别列表。我关闭了 Categories 表中 ID 的 isIdentity 选项,因为我打算使用 XML 中的 ID。

XML 示例:

<cat>
<id>17</id>
<name>Category name</name>
<parent_id>0</parent_id>
</cat>

然后,我写了方法,尝试通过ID获取类别并更新,或者插入新的:

var category = _categoryService.GetCategoryById(Id);
        if (category != null)
        {
            category.Name = model.Name;
            category.ParentCategoryId = model.ParentCategoryId;
            category.UpdatedOnUtc = DateTime.UtcNow;
            category.Published = true;
            category.Deleted = false;

            _categoryService.UpdateCategory(category);
        }
        else
        {
            category = new Core.Domain.Catalog.Category();

            category.Id = model.Id;
            category.ParentCategoryId = model.ParentCategoryId;
            category.Name = model.Name;
            category.UpdatedOnUtc = DateTime.UtcNow;
            category.CreatedOnUtc = DateTime.UtcNow;
            category.Published = true;
            category.Deleted = false;

            _categoryService.InsertCategory(category);
        }

然后是最奇怪的 - 应用程序抛出异常:无法将值 NULL 插入列 'Id',表 'nopCommerce.dbo.Category';列不允许空值。插入失败。 该语句已终止。 但即使在调试器中,类别 ID 也不为空.. 寻求帮助! 提前致谢!

更新:InsertCategory 是一种标准的 nopCommerce 方法:

 /// <summary>
    /// Inserts category
    /// </summary>
    /// <param name="category">Category</param>
    public virtual void InsertCategory(Category category)
    {
        if (category == null)
            throw new ArgumentNullException("category");

        _categoryRepository.Insert(category);

        //cache
        _cacheManager.RemoveByPattern(CATEGORIES_PATTERN_KEY);
        _cacheManager.RemoveByPattern(PRODUCTCATEGORIES_PATTERN_KEY);

        //event notification
        _eventPublisher.EntityInserted(category);
    }

【问题讨论】:

    标签: asp.net-mvc-3 entity-framework nopcommerce


    【解决方案1】:

    您的代码看起来不错,这里展示的似乎还不错。我会说您的 InsertCategory 方法有问题,该方法很可能没有使用 id。这只是一个猜测...如果这不是答案,也许您可​​以告诉我们您的答案。

    【讨论】:

    • public void Insert(T entity) { try { if (entity == null) throw new ArgumentNullException("entity"); this.Entities.Add(entity); this._context.SaveChanges(); } catch (DbEntityValidationException dbEx) { throw dbex; } } 是一种标准的 nopCommerce 方法。当我调试它时,实体不为空并且有 ID,这是最奇怪的事情......
    • 伙计,我感受到了你的痛苦。希望您找到解决方案并将其作为答案发布,以便其他人不会长时间遇到同样的问题。也许向 nopcommerce 提交错误?干杯
    【解决方案2】:

    我刚刚发现,我需要更改映射类以及数据库,从 ID 中删除自动编号选项。那是另一个痛苦,但解决方案是:

    而不是this.HasKey(c=&gt;c.Id) 使用:

    this.Property(c=>c.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None) ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      相关资源
      最近更新 更多