2016-01-20 43 views
1

当我运行下面的代码,我得到实体框架失败,因为相同类型的另一个实体已具有相同的主键值。外键

try { 
    var questionRepo = new QuestionRepository(db); 
    var question = new Question(); 

    question.QuestionText = text; 
    question.QuestionCategory = SelectedQuestionCategory; 
    db.QuestionCategory.Attach(SelectedQuestionCategory); 

    //Tried adding 
    //db.Entry(question).State = System.Data.Entity.EntityState.Added; 

    questionRepo.Add(question); 
    db.SaveChanges(); 
} catch (Exception ex) { 
    Debug.WriteLine(ex.Message); 
    return; 
} 

没有错误,当我以前没有使用过的QuestionCategory,但我得到一个错误,如果我有。

该错误仅在我已经在我的数据库中选择SelectedQuestionCategory时有问题。我再次检查了数据库,Question的主键位于id列,而不是QuestionCategory

我得到的错误是:

附加型“QuestionCategory”的实体失败 因为同类型的另一实体已经具有相同的主 键值。

为什么它在等外键上失败,而外键不是组合主键或主键?

回答

1

可能是您添加问题时EntityFramework尝试向连接到问题的数据库添加另一个QuestionCategory新实例。 尝试使用Id 更改QuestionCategory的对象状态。

question.QuestionCategory = null; 
question.QuestionCategoryId = SelectedQuestionCategory.Id; 
0

首先,问题似乎与QuestionCategory上的PK而不是Question有关。 SelectedQuestionCategory如何设置?你是否用你想要的值new()了一个QuestionCategory实例?如果是这样,你无意中尝试添加具有相同PK的第二个实例。在这种情况下,您可能会更好地从db.QuestionCategory中检索现有实例,因为您已经拥有了DbContext。

+0

SelectedQuestionCategory是通过下拉菜单{binding} wpf查看的值。 –

+0

研究如何创建这些实例,并确保在您从数据库中提取这些实例时,您没有使用.AsNotTracking()来跟踪它们。 – richardsonmarkj

相关问题