Govind Samrow
Govind Samrow

Reputation: 10179

Create object from existing object Entity framework c#

I want to copy full information of record to another in EF C#:

List<Cohort> AnYearsCohorts = oDB.Cohorts.Where(x=>x.Year == oCh.Year).ToList();
foreach (Cohort ochort in AnYearsCohorts)
{
    Cohort nChort = new Cohort();
    nChort = ochort;
    nChort.Year = Year;
    nChort.ID = 0;
    oDB.Cohorts.Add(nChort);
}
oDB.SaveChanges();

But got following error:

{"The property 'ID' is part of the object's key information and cannot be modified. "}

Upvotes: 0

Views: 140

Answers (1)

Jaimin Dave
Jaimin Dave

Reputation: 1222

You probably have set ID as primary key and auto incremented so you can not change ID field explicitly in code. Either remove ID as key or let ID increment automatically.

Upvotes: 3

Related Questions