Babak Fakhriloo
Babak Fakhriloo

Reputation: 2126

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

I am developing an asp.net mvc 3.0 app and using EF 4.1 for my data access layer and unit of work pattern.

Here are my models :

 public class UpdateUserViewModel
    {
        public User User { get; set; }
    }

public partial class Role
    {
        public int Id { get; set; }

     }


    public partial class User
    {
        public Guid Id { get; set; }

        public virtual Role Role { get; set; }
    }

I pass UpdateUserViewModel to a view and then post the form in the view to the following action :

public ActionResult UpdateUser(User user)
        {
            var userObj = unitofwork.UserRepository.GetByID(user.Id);

            TryUpdateModel(userObj, "User");

            userObj.Role = unitofwork.RoleRepository.GetByID(user.Role.Id);

            unitofwork.UserRepository.Update(userObj);

            unitofwork.Save();
        }

Problem raises when I Update user role in the view (it is a dropdown list) and try to update it. it gives me the following error :

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

But if i dont update the user role, it works fine.

Would you help me please ?

Upvotes: 0

Views: 2653

Answers (1)

Chris
Chris

Reputation: 3298

You can call TryUpdateModel with an 'exclude' list of properties - and just exclude the ID property if that's appropriate for your scenario.

e.g.

TryUpdateModel(user, null, null, new [] { "Id"} )

Upvotes: 1

Related Questions