Entity Framework the use of reference
I use
p.AuthorsReference.EntityKey = new System.Data.EntityKey("PetitionsContainer.Authors", "Id", authorId);
but I get entities in PetitionsContainer.Questions
participate in 开发者_开发问答the QuestionAuthor
relationship.
0 related 'Author' were found. 1 'Author' is expected.
Now, the Author
with the Id authorId
is already in the database.
It is true that each question must have 1 author.
Though, can't I use AuthorsReference
instead of something like p.Authors.Add(new Author())
?
If you set up the reference you must also fill the author. You can try using this:
// Attach a dummy author to the context so that context believes that you
// loaded the author from the database
Author a = new Author { Id = authorId };
context.Authors.Attach(a);
// Now assign existing author to the question
question.Author = a;
精彩评论