0

I've got the following piece of code:

var SelectAll = eF.People.ToList();

People P1 = new People();
P1.PersonID = 4;
P1.Name = "Iman";
P1.Family = "Rajabi";
P1.Age = 40;

eF.People.Add(P1);
eF.SaveChanges();

I get the following error when adding a person:

DbUpdateException

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • Do you have primary key set up? Please share your entity's structure. – BenceL Aug 10 '20 at 09:11
  • Here is the answer for your problem https://stackoverflow.com/questions/15322894/because-it-has-a-definingquery-and-no-insertfunction-element-exists-in-the-mo#answers-header – Sowmyadhar Gourishetty Aug 10 '20 at 09:15
  • You need to define the PK via Fluent api – MatteoCracco97 Aug 10 '20 at 09:22
  • Navigate to this link, I think this will solve your error. [How to avoid System.Data.Entity.Infrastructure.DbUpdateException](https://stackoverflow.com/questions/20762923/how-to-avoid-system-data-entity-infrastructure-dbupdateexception/20765016) – Abdul Haseeb Aug 10 '20 at 12:04

1 Answers1

0

As mentioned above, the field PersonID is possibly a primary key. Often in SQL server in addition to this, a primary key is often an identity column, meaning that SQL Server typically manages these values for you. If this is the case, you should not set the PersonID value. In addition, you may need to annotate the PersonId column in your model.

For some examples have a look here https://learn.microsoft.com/en-us/ef/core/modeling/keys?tabs=data-annotations

Craig Gers
  • 544
  • 3
  • 9