I’m creating import from XML function for categories.
First of all, using XDocument, I create list of categories to be added. I turned off isIdentity option for ID in Categories table, because I’m planning to use ID from XML.
XML example:
<cat>
<id>17</id>
<name>Category name</name>
<parent_id>0</parent_id>
</cat>
Then, I wrote method, which tries to get category by ID and update, or insert new:
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);
}
And then comes the most weird – application throws exception: Cannot insert the value NULL into column ‘Id’, table ‘nopCommerce.dbo.Category’; column does not allow nulls. INSERT fails.
The statement has been terminated.
BUT even in debugger, category ID is not null.. Asking for help!
Thanks in advance!
Update: InsertCategory is a standard nopCommerce method:
/// <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);
}
I just found out, that I need to change mapping class as well as database, removing autonumber option from ID. That was another pain, but solution is:
instead of
this.HasKey(c=>c.Id)use: