JB06
JB06

Reputation: 1931

Adding an entity to the context

Why is this simple add not working! I get a previous record from the database, instantiate a new entity to add by using the previous record's data, except I increment the report number by 1. I keep getting the error "The property 'ReportNbr' is part of the primary key and cannot be modified." I thought this error was when you tried to update an existing entities' primary key field.

Here's my object and previous record that I use.

var previousRecord = _repo.GetLatestRecord();
            var recordToAdd = new Record()
            {
                Year = previousRecord.Year,
                Month = previousRecord.Month,
                ReportNbr = ++previousRecord.ReportNbr,
                ...//other info
            };
_repo.AddRecord(recordToAdd);

The three fields show are the primary key to the table. Any help would be greatly appreciated.

Upvotes: 1

Views: 43

Answers (1)

Mike
Mike

Reputation: 3311

If you have change tracking on, the

++previousRecord.ReportNbr 

is updating the previousRecord.

Try

ReportNbr = previousRecord.ReportNbr + 1; 

Upvotes: 2

Related Questions