The property 'Id' is part of the object's key information and cannot be modified

早过忘川 提交于 2019-12-10 21:50:09

问题


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 --

  1. User creates a new topic it should add a topic record on the database
  2. Get the topic Id and set that Id to the Post's TopicId
  3. 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!


回答1:


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:

TryUpdateModel(updateTopic,  "", null, new string[] { "Id" });

I'm guessing that one property named "ID" is also submitted into this action, causing the error.



来源:https://stackoverflow.com/questions/5820285/the-property-id-is-part-of-the-objects-key-information-and-cannot-be-modified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!