entity framework error : {"The property 'Id' is part of the object's key information and cannot be modified. "}

During adding an instance of a class to the context following error is thrown how can i fix this pls? i use EF5 with MVC

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

below i also changed  [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] to  [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]  and it did not work, i also tried not passing Id at all or passing id during forming the instance in var comp = new Company { CompanyName = company.CompanyName}; but did not do any good unfortunately





mvc controller calls the repository function as below
 var comp = new Company { CompanyName = company.CompanyName};
            _repo.AddCompany(comp);

Open in new window


then error is thrown during :   _ctx.Companies.Add(newCompany); line below
 public bool AddCompany(Company newCompany)
        {
            try
            {
                _ctx.Companies.Add(newCompany);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

Open in new window



Company class is as follows;

 public class Company
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column("Id")]
        public int Id { get; set; }
        public string CompanyName { get; set; }
        public ICollection<Topic> Topics { get; set; }
    }

Open in new window

nicedoneAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AndyAinscowFreelance programmer / ConsultantCommented:
try changing
public int Id { get; set; }
to
public int Id { get;  }
nicedoneAuthor Commented:
@AndyAinscow,

after changing  to

public int Id { get; }

I get the error:

Company.Id get must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors.

making it abstract eliminates the build error but then it makes the class abstract ,property abstract and in other parts of my application it caused other error which i did not fully check really.

do you think i should not implement auto property ?
AndyAinscowFreelance programmer / ConsultantCommented:
And this (or similar - I'm trying to effective disable set) ?
public int Id { get; }
private Id { set; }
Protecting & Securing Your Critical Data

Considering 93 percent of companies file for bankruptcy within 12 months of a disaster that blocked access to their data for 10 days or more, planning for the worst is just smart business. Learn how Acronis Backup integrates security at every stage

nicedoneAuthor Commented:
@AndyAinscow;

public int Id {get;private set;}  
did the magic. and it works now thanks

but did not understand fully why it was getting angry about? do you know why i ran into this issue?
AndyAinscowFreelance programmer / ConsultantCommented:
Error message you posted (with my highlighting):

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

Having a public set violates that by saying it can be modified, hiding the set prevents it being modified by other classes.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Prakash SamariyaIT ProfessionalCommented:
You might be getting error while updating EF, and Primary column must be changed!!  

Please check and verify the same
- Set a PK (Primary Key) on  ID column in Company table if not.
- Check XML code of myEntityModel and find: (Remove other columns and keep the primary/identity column only in <Key> section
<EntityType Name="Company">
    <Key>
        <PropertyRef Name="ID" />
        <PropertyRef Name="OtherColumnID" />   <!-- This second line caused problem -->
    </Key>
   ...
</EntityType>

Open in new window

- Remove Table<Company> from EntityModel and Add it again! Sometimes it works
- IF nothing works from above, remove .edmx and re-create it!
AndyAinscowFreelance programmer / ConsultantCommented:
@Prakash Samariya

Please read the other comments, especially the one where it states it has been solved by doing what I suggested in the C# code behind.
Prakash SamariyaIT ProfessionalCommented:
@AndyAinscow;
"but did not understand fully why it was getting angry about? do you know why i ran into this issue?"
I think the author [nicedone] is curious to know the possible reasons, so I posted that one along-with good possible solutions!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.