将此添加到类别时保存产品的新记录(重复)

时间:2014-08-13 05:37:32

标签: c# asp.net entity-framework code-first updates

在EF Code First中我有两张桌子(产品 - 类别) 关系很多很多 我创建了一个产品并添加到类别中 (即时通讯使用autofac)

Product _product = null;
using (var builder = EngienContext.container.BeginLifetimeScope())
{
     var _productService = builder.Resolve<IProductService>();
     _product = _productService.InsertProduct(new Product()
           {
                NameEn = nameEn,
                ShortDescription = shortDescription,
                FullDescription = fullDescription,
                DateTimeCreate = DateTime.Now,
                CreatedOnUtc = DateTime.UtcNow,
                ActiveStatus = true,
                AdminLockReadOnly = false,
                Deleted = false,
            });

    var _categoriesService = builder.Resolve<ICategoriesService>();
    Categories _category = _categoriesService.GetCategoryByGuid(_categoryGuid);
    _category.Products.Add(_product);
   _categoriesService.UpdateCategory(_category);

}

但是当我将产品添加到_category.products时,在产品表上创建产品的新记录,并将新记录的ID添加到映射表。 。

更新时的表格值:

product table:

ID         Name         ShortDescription
1:         test      test table id must be 1
2:         test      test table id must be 1
3:

Category table:

ID        Name         Description
1:      categor1      test category1
2:

product_category_mapping table:

ProductID     CategoryID   
  2                1

但我想:

product table:

ID         Name         ShortDescription
1:         test      test table id must be 1
2: 

Category table:

ID        Name         Description
1:      categor1      test category1
2:

product_category_mapping table:

ProductID     CategoryID   
  1                1

我的服务更新方法:

    public virtual void UpdateCategory(Categories Category)
    {
        if (Category == null)
        {
            throw new ArgumentNullException("Category");
        }

        _categoryRepository.Update(Category);
    }

我在存储库中的更新方法:

    public TEntity Update(TEntity item)
    {
        return _context.Update(item);
    }

我在DbContext中的更新方法:

public T Update<T>(T item) where T : class
    {

            if (item == null)
                throw new ArgumentNullException("entity");
            var entry = this.Entry(item);
            if (entry != null) 
            {
                entry.CurrentValues.SetValues(item);
            }
            else
            {
                this.Attach(item);
            }
            this.SaveChanges();
    }

我对地图的关系:

            this.HasMany(p => p.Categories)
            .WithMany(c => c.Products)
            .Map(m => m.ToTable("Product_Category_Mapping"));

0 个答案:

没有答案