I have an object called GeneralInformation
that I want to duplicate in my table, however, obviously this new record will have a different GeneralInformationID
.
My goal is to have the user click a link that goes to domain.com/proforma/copyversion/<id>
where it does the action from my controller below.
Here's my Controller:
[HttpPost]
public ActionResult CopyVersion(int? id)
{
Version version = db.Versions.Find(id);
GeneralInformation generalInformation = version.GeneralInformation;
var generalInformationCopy = generalInformation;
generalInformationCopy.GeneralInformationID = null;
db.Entry(generalInformationCopy).State = EntityState.Added;
return View("Index");
}
I am receiving an error message of: "Cannot convert source type 'null' to target type 'int'
. The GeneralInformationID
is the Primary Key and the Identity, auto generated column.
I have two tables in my Entity Model:
GeneralInformation
-------------------
GeneralInformationID (PK)
VersionID
FirstName
LastName
And my second table:
Version
--------
VersionID (PK)
OwnerID
VersionOwner
VersionNumber
isLocked
How do I make a COPY of the GeneralInformation object that I have?
EDIT - Updated Model: (Contains an error)
[HttpGet]
public ActionResult CopyVersion(int? id)
{
Version version = Db.Versions.Find(id);
version.isLocked = true;
Db.Entry(version).State = EntityState.Modified;
// Add new Version of the Proforma
var newVersion = new Version() {
VersionParentID = version.ProformaID,
OwnerID = version.OwnerID,
AuthorName = version.AuthorName,
VersionNumber = (version.VersionNumber + 1)
};
Db.Entry(newVersion).State = EntityState.Added;
Db.SaveChanges();
// Create a copy of `GeneralInformation` and UPDATE the VersionID
var generalInformation = proformaDb.GeneralInformations.Create();
proformaDb.Entry<GeneralInformation>(version.GeneralInformation).CurrentValues.SetValues(generalInformation);
Db.GeneralInformations.Add(generalInformation);
Db.SaveChanges();
// Redirect to the Proforma Index View
return RedirectToAction("Index");
}
I'm getting the following error:
The property 'VersionID' is part of the object's key information and cannot be modified.
The VersionID is the PK on the table.