1

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);
TyForHelpDude
  • 4,828
  • 10
  • 48
  • 96

2 Answers2

0

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

Doan Cuong
  • 2,594
  • 4
  • 22
  • 39
0

You can't change the part of id while update the database so if you want to update the filed you should remove it first then insert it with the new value this is the safety way to update the primary key (if the primary key is composite key ) and you want to update on of the primary key