I have a sample web app that I am writing and im confused why i'm getting this
The property 'Id' is part of the object's key information and cannot be modified.
when i'm not updating the 'Id'?
Ok, so this is what I am trying to do.
I have 2 tables Topics and Posts and --
- User creates a new topic it should add a topic record on the database
- Get the topic Id and set that Id to the Post's TopicId
- Get that post's Id and set it as Topic's LastPostId
I'm re updating the post so whenever I need to display the last post made to the topic I don't need to do the "sort by date for all the post inside this topic". There should be a better way to do this..
When I debug i see that The topic category Id is being set as the Topic Id which i do not have in my update code.
//
// insert new topic to database
Topic topic = new Topic();
topic.CategoryId = int.Parse(RouteData.Values["id"].ToString());
topic.Title = postModel.Title;
topicRepo.Add( topic );
topicRepo.Save();
//
// insert post to database
PostRepository postRepo = new PostRepository();
Post post = new Post();
post.TopicId = topic.Id;
post.Body = postModel.Body;
string strUserId = UserAccount.FormatUserName( User.Identity.Name );
post.CreatedByUser = strUserId;
post.CreationDate = DateTime.Now;
postRepo.Add( post );
postRepo.Save();
// ***********************
// update topic last post
// ***********************
Topic updateTopic = topicRepo.GetTopic( topic.Id );
updateTopic.LastPostId = post.Id;
TryUpdateModel( updateTopic );
if ( ModelState.IsValid )
topicRepo.Save();
Thanks!
This happens because TryUpdateModel tries to update all posted values. So if you have one or more values that you don't want updated, you have to do this manually.
For instance:
I'm guessing that one property named "ID" is also submitted into this action, causing the error.