Entitiy insert data."The property 'ID' is part of the object's key information and cannot be modified" error

TyForHelpDude picture TyForHelpDude · Jun 16, 2014 · Viewed 9k times · Source

current is new instance of myclass and context.classRepo.bringcontentwithid(userid) return an instance of it. I assign this value to my new object current then try to insert is as new row in my datatable but it gives me error like "The property 'ID' is part of the object's key information and cannot be modified"

its the point I did not understand is I dont want to modify anything I just assing an instance make chenges and insert it as new data.

How can I fix this ?

   myclass current = new myclass();

    current = context.classRepo.bringcontentwithid(userid);
                    if (current != null)
                    {
                        current.id = context.classRepo.YeniBildirimIdGetir();
                        current.GONDERILDI = "1";
                        context.classRepo.Insert(current);

Answer

Doan Cuong picture Doan Cuong · Jun 16, 2014

By default, EF take your ID as auto-increment identity, therefore, you will get that error while trying to manually assign ID. To make EF understand that ID will be manually assigned, just decorate your property with [DatabaseGenerated(DatabaseGeneratedOption.Assign)] as follow:

public class myClass()
{
    [DatabaseGenerated(DatabaseGeneratedOption.Assign)]
    public int ID {get;set;}
}

please make sure to import namespace System.ComponentModel.DataAnnotations.Schema