问题描述
|
问题有作者。
添加新问题时,我使用getCurrentUser()从数据库中提取作者;
Question q=new Question();
q.Author=getCurrentUser();
context.Questions.Add(q);
这将生成EntityKey属性,仅当该属性的当前值为null时才能设置。因为作者已经具有ID的值。我应该如何指定作者已经在数据库中?
解决方法
如果要使用此简单代码,则必须使用相同的上下文实例来添加问题和加载用户。如果要使用两个上下文实例,则必须修改代码:
Question q=new Question();
User u = getCurrentUser();
context.Users.Attach(u);
q.Author = u;
context.Questions.Add(q);
在某些情况下,也有必要使用“ 2”方法将用户从上下文中分离出来。