2013-09-23 25 views
0

我有一个由“实体”和“测量”两个实体使用的实体“问题”。逻辑是,创建一组问题,但是当向调查添加问题时,创建一个克隆,以便在问题集中编辑问题不会改变调查中的问题。 但是,由于有明确的更新功能,克隆(在调查中)需要知道它的来源(问题集中的问题)。在创建新的时候尝试引用现有实体时出错

我解决了这个在问题补充一个

public virtual Question CreatedFrom { get; set; } 

。然而,当我现在要做的是在我的控制器

oldQ = _questionRepository.GetById(qTransfer.Id); 
q = new Question(oldQ); 
q.CreatedFrom = oldQ; 
q.Id = 0; 

其中Q的拷贝构造函数使得问题的值(创建克隆)的完整副本如下。

最后这在我的回购

if (item.Id == 0) 
{ 
    Add(item); //this calls Add on dbset 
} 
ActiveContext.SaveChanges(); 

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

如果我注释掉q.CreatedFrom = oldQ;那么我不会再犯错误了。

我想要的仅仅是当我创建一个克隆时引用问题父。我仍然希望原始问题能够独立运作。 我当然可以简单地将CreatedFrom替换为CreatedFromId,但我认为用直接引用会很好。

更新

这里是我的克隆代码。在克隆时,我复制了CreatedFrom的引用,但是在被克隆的对象中应该为null。

public Question(Question q) 
    { 
     Id = q.Id; 
     Description = q.Description; 
     CreatedFrom = q.CreatedFrom; 
     Type = q.Type; 
     AddedTime = q.AddedTime; 
     DeletedTime = q.DeletedTime; 
     SortIndex = q.SortIndex; 
     IsPageBreak = q.IsPageBreak; 

     List<QuestionAlternative> list = new List<QuestionAlternative>(); 
     QuestionAlternative alternative; 
     foreach (var alt in q.Alternatives) 
     { 
      alternative = new QuestionAlternative(alt); 
      alternative.Id = 0; 
      list.Add(alternative); 
     } 
     Alternatives = list; 
    } 

的QuestionAlternative反过来有一个拷贝构造函数像这样:

public QuestionAlternative(QuestionAlternative qa) 
    { 
     Id = qa.Id; 
     Text = qa.Text; 
     HasTextAnswer = qa.HasTextAnswer; 
    } 
+0

您能在拷贝构造函数中显示克隆代码吗? – Colin

+0

很高兴,我更新了问题 –

回答

2

我觉得你的问题是在这里:

"While cloning I copy the reference for CreatedFrom however that should be null in the object being cloned"

oldQ.CreatedFrom引用可能是在点空值构造函数被调用,但它仍然是一个引用类型。因此,当您拨打q.CreatedFrom = oldQ时,oldQ.CreatedFrom也被设置为相同的参考 - 即它将引用自身。

如果您将CreatedFromID添加为问题的属性并使用它,那么我认为实体框架将为您修复引用。所以性能应该是这样的:

public int? CreatedFromID { get; set; } 

[ForeignKey("CreatedFromID ")] 
public virtual Question CreatedFrom { get; set; } 

而且在构造函数:

public Question(Question q) 
{ 
    //Stop setting the reference property 
    //CreatedFrom = q.CreatedFrom; 

    //Set the foreign key instead   
    CreatedFromID = q.CreatedFromID; 

    //EDIT - as discussed in the comments it would make more sense like: 
    //CreatedFromID = q.ID; 

} 

这是值得一读Save the Grief and Use That Foreign Key

编辑

您不必添加外键来解决这个问题。如果您首先将引用设置为逻辑正确的东西,那么它也应该修复它。

public Question(Question q) 
{ 
    Id = 0; 
    CreatedFrom = q; 
} 
+0

我在尝试解决方案,但是当我运行迁移更新时,我在添加迁移中得到此“序列不包含任何元素”。 –

+0

听起来像种子方法中的问题 – Colin

+0

它会但我的种子是empty.this描述我的问题,但我没有重新命名的ID,所以不完全合理:http://entityframework.codeplex.com/workitem/ 569 –

相关问题