2009-06-25 83 views
1

我试图使用方法:LINQ to SQL的实体运营

// this is a BreakHistory class from the ADO.NET Data Entity Model _entities 
_entities.AddToBreakHistory(this); 
_entities.SaveChanges(); 

和我得到“一个实体对象不能被IEntityChangeTracker的多个实例的引用。”错误

我在想,我的更新代码:

_entities.ApplyPropertyChanges(this.EntityKey.EntitySetName, this); 
_entities.SaveChanges(); 

,我想我可能会得到相同类型的错误。

我是否必须获取原始的BreakHistory对象?

var originalBreakHistory = (from bh in _entities.BreakHistorySet where bh.BreakHistoryID = id select bh).FirstOrDefault(); 

- 更新于4:40 PM 当天看来,我可能会具有可能与另一个问题。 我将管理器实体对象添加到当前BreakHistory实体,因为它们是相关的,并且我收到此错误: “两个对象之间的关系无法定义,因为它们连接到不同的ObjectContext对象。”

难道那个错误是因为我使用相同的实体模型,但在实体对象上调用“new”并从DB中加载它们?

下面是我的一些代码:

protected void lstBreaks_ItemCommand(object source, RepeaterCommandEventArgs e) 
{ 
    var bh = new BreakHistory().CurrentBreakRequest(int.Parse(e.CommandArgument.ToString())).CurrentManagerIs(GetManagerEntityByUserName()); 

    switch (e.CommandName) 
    { 
     case "Approve": 
      bh.Approve(); 
      break; 
     case "Deny": 
      bh.Deny(); 
      break; 
     case "Push": 
      bh.Push(); 
      break; 
    } 

    bh.Save(); 

    LoadBreakList(); 
} 

上例中的代码的批准 - bh.Approve()看起来是这样的:

public BreakHistory Approve() 
{ 
    this.DateApproved = DateTime.Now; 
    this.ManagerApprove = CurrentManager; 

    return this; 
} 

经理可以批准,拒绝或推管理员通过ManagerID与BreakHistory关联的请求。

回答

0

如果您正在检索现有记录,则不应该使用新的操作符。这可能是什么挂在你身上。

确保您的所有更新都使用相同的DataContext对象。出于多种原因,很难将对象从一个DataContext移动到另一个DataContext。

+0

我还在学习Linq和整个实体模型结构。你说得对,我使用了两个完全独立的DataContext。 – kntcnrg 2009-06-29 12:54:07