PDA

View Full Version : سوال: ذخیره شدن به صورت Record جدید هنگام update کردن در EF -Code Fist (فوری!!!!)



mpk2119
دوشنبه 27 مرداد 1393, 17:42 عصر
سلام
من توی Entity Framework - Code First دو جدول دارم با اسم های product و category که رابطه بینشون چند به چند (many to many) هست
من یک product جدید ثبت کردم و category موجود رو بهش ادد کردم (برای ثبت در جدول mapping )
(من از 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.Add(_product); _categoriesService.UpdateCategory(_category); اجرا میشه به جای اینکه تو جدول mapping آیدی product و آیدی category ثبت بشه اول یه product جدید تو جدول product ثبت میکنه و بعد همون رو تو جدول mapping با category ارتباط میده

اتفاقی که میوفته:

جدول product:


ShortDescription
Name

ID


test table id must be 1

test
1


test table id must be 1

test
2



جدول category:


Name
ID


category1
1



جدول mapping:


CategoryId
ProductId


1

2





اتفاقی که من میخوام بیوفته:

جدول product:


ShortDescription
ID


test table id must be 1
1



جدول category:


Name
ID


category1
1



جدول mapping:


CategoryId
ProductId


1
1




متد آپدیت من در 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();
}

رابطه بین این دو کلاس در mapping:
this.HasMany(p => p.Categories)
.WithMany(c => c.Products)
.Map(m => m.ToTable("Product_Category_Mapping"));


اما من فکر میکنم مشکل تو استفاده از autofac هسن چون وقتی به جای
_category.Products.Add(_product);
_categoriesService.UpdateCategory(_category);
از

_product.categories.add(_category);
_productService.UpdateProduct(_product);

استفاده کردم این Error رو داد:

this error generated: exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.



خواهش میکنم سریعتر جواب بدین , پایان مهلت تحویل پروژه ام نزدیکه. . .