2014-10-06 61 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); 
} 
相关问题