2014-10-06 51 views
0

我有2個控制器和存儲庫,Gifts和Registries。禮物可以有一個註冊表,當我嘗試創建一個新的禮物時,我收到錯誤「一個實體對象不能被多個IEntityChangeTracker實例引用」。保存相關實體時,「一個實體對象不能被IEntityChangeTracker的多個實例引用」

的禮物具有以下屬性:

public class Gift 
{ 
    public int GiftId { get; set; } 

    public string Name { get; set; } 

    public Registry Registry { get; set; } 
} 

我的代碼添加禮品如下:

在控制器:

private IGiftRepository _giftRepository; 
    private IAccountRepository _accountRepository; 

    public GiftController() 
    { 
     this._giftRepository = new GiftRepository(new ApplicationDbContext()); 
     this._accountRepository = new AccountRepository(new ApplicationDbContext()); 
    } 

    public GiftController(IGiftRepository giftRepository) 
    { 
     this._giftRepository = giftRepository; 
    } 

    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Create(Gift gift) 
    { 
     if (ModelState.IsValid) 
     { 
      Registry registry = _accountRepository.GetLoggedInRegistry(User.Identity.GetUserId()); 

      gift.Registry = registry; 

      await _giftRepository.AddGiftAsync(gift); 

      return RedirectToAction("Home", "Admin"); 
     } 

     return View(gift); 
    } 

這裏是在代碼repository:

public async Task<bool> AddGiftAsync(Gift gift) 
    { 
     try 
     { 
      _context.Gifts.Add(gift); 
      await _context.SaveChangesAsync(); 
     } 
     catch (Exception) 
     { 
      return false; 
     } 

     return true; 
    } 

在_content.Gifts.Add(禮物)我得到以下錯誤:「一個實體對象不能被多個IEntityChangeTracker實例引用。」我意識到是由於我配置了我的上下文的方式,但我不確定我需要做些什麼改變才能實現這個工作。

回答

0

嘗試初始化存儲庫這樣的:

public GiftController() 
{ 
    var context = new ApplicationDbContext(); 
    this._giftRepository = new GiftRepository(context); 
    this._accountRepository = new AccountRepository(context); 
} 
相關問題