Question has Author. When adding a new question, I take the author from the database with getCurrentUser();
Question q=new Question();
q.Author=getCurrentUser();
context.Questions.Add(q);
this generates The EntityKey property can only be set when the cu开发者_高级运维rrent value of the property is null. because Author already has a value for Id. How should I specify that the author is already in the database?
You must use the same context instance for both adding the question and loading the user if you want this simple code to work. If you want to use two context instances you must modify your code:
Question q=new Question();
User u = getCurrentUser();
context.Users.Attach(u);
q.Author = u;
context.Questions.Add(q);
In some cases it can be also necessary to detach user from the context in getCurrentUser
method.
精彩评论