开发者

entity framework navigation property with object from database

开发者 https://www.devze.com 2023-03-09 05:32 出处:网络
Question has Author. When adding a new question, I take the author from the database with getCurrentUser();

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号