我有 3 个数据库表:Vendors、Regions 和 VendorRegions:
Vendors
-------------------
VendorID (PK)
Name
Regions
-------------------
RegionID (PK)
Name
VendorRegions
-------------------
VendorID (PK)
RegionID (PK)
在我创建供应商的页面上,我在复选框列表中列出了每个区域。对于检查的每个区域,我想将 VendorID 和 RegionID 添加到 VendorRegions 表中。
我正在使用 Entity Framework 、C# 和 MVC 3。
这是我的 Controller 代码:
public class VendorsController : Controller
{
readonly IVendorsRepository _vendorsRepository;
readonly IRegionsRepository _regionsRepository;
public VendorsController()
{
_vendorsRepository = new SqlVendorsRepository();
_regionsRepository = new SqlRegionsRepository();
}
[HttpPost]
public ActionResult Create(VendorViewModel viewModel, string[] Regions)
{
var vendor = new Vendor();
TryUpdateModel(vendor);
if (ModelState.IsValid)
{
vendor.Regions.Clear();
foreach (var regionId in Regions)
{
vendor.Regions.Add(_regionsRepository.GetRegion(Int32.Parse(regionId)));
}
_vendorsRepository.SaveVendor(vendor);
return RedirectToAction("Index");
}
return View(viewModel); // validation error, so redisplay same view
}
}
这是我的供应商存储库代码:
public class SqlVendorsRepository : IVendorsRepository
{
private readonly MyDBEntities _entities;
public SqlVendorsRepository()
{
_entities = new MyDBEntities();
}
public void SaveVendor(Vendor vendor)
{
// If it's a new vendor, just attach it to the DataContext
if (vendor.VendorID == 0)
_entities.Vendors.Context.AddObject("Vendors", vendor); // ERROR HERE
else if (vendor.EntityState == EntityState.Detached)
{
// We're updating an existing vendor, but it's not attached to this data context, so attach it and detect the changes
_entities.Vendors.Context.Attach(vendor);
_entities.Vendors.Context.Refresh(System.Data.Objects.RefreshMode.ClientWins, vendor);
}
_entities.Vendors.Context.SaveChanges();
}
}
当我尝试在
_entities.Vendors.Context.AddObject("Vendors", vendor);
处保存我的供应商时发生错误。以防万一,这是我的 Regions 存储库代码:public class SqlRegionsRepository : IRegionsRepository
{
private readonly MyDBEntities _entities;
public SqlRegionsRepository()
{
_entities = new MyDBEntities();
}
public IQueryable<Region> Regions
{
get { return _entities.Regions.AsQueryable(); }
}
public Region GetRegion(int id)
{
return Regions.FirstOrDefault(st => st.RegionID == id);
}
}
这似乎是一件简单的事情,但我不知道如何克服这个错误。有任何想法吗?
最佳答案
您有两个不同的存储库,每个存储库都有一个 单独的 数据上下文 - 这是根本问题 - 您的数据上下文应该由所有存储库共享,即您可以通过构造函数注入(inject)来注入(inject)它:
MyDBEntities entities = new MyDBEntities();
_vendorsRepository = new SqlVendorsRepository(entities);
_regionsRepository = new SqlRegionsRepository(entities);
关于c# - "An entity object cannot be referenced by multiple instances of IEntityChangeTracker",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7152773/