Entity insertion data. & Ldquo; The 'ID' property is part of the object's key information and can not be changed & ldquo; Error

advertisements

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


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