当我尝试对对象进行复制,重新分配PK ID,然后将对象添加到GeneralInformation模型时,我收到错误消息。
我的实体模型中有两个表:
Version
--------
VersionID (PK)
OwnerID
VersionOwner
VersionNumber
我的第二张桌子:
GeneralInformation
-------------------
GeneralInformationID (Identity)
VersionID (PK)
FirstName
LastName
如何制作我拥有的GeneralInformation对象的COPY?
这是我的控制器:
[HttpGet]
public ActionResult CopyVersion(int? id)
{
Version version = Db.Versions.Find(id);
version.isLocked = true;
Db.Entry(version).State = EntityState.Modified;
// Add new Version
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
GeneralInformation generalInformation = new GeneralInformation();
// Make both VersionID's the same.
generalInformation.VersionID = newVersion.VersionID;
version.GeneralInformation.VersionID = newVersion.VersionID;
var currentValues = Db.Entry<GeneralInformation>(version.GeneralInformation).CurrentValues;
currentValues.SetValues(generalInformation); //**ERRORS OUT ON THIS LINE**
generalInformation.VersionID = newVersion.ProformaID;
Db.GeneralInformations.Add(generalInformation);
// Redirect to the Proforma Index View
return RedirectToAction("Index");
}
我收到以下错误:
The property 'VersionID' is part of the object's key information and cannot be modified.
注意: VersionID
GeneralInformation
是我正在尝试复制的桌子上的PK。
注意: 1 to 0..1
的版本与GenralInformation之间存在关联
答案 0 :(得分:1)
“常规信息”实体的“VersionId”属性应为外键而不是主键。