【发布时间】:2014-10-16 14:59:09
【问题描述】:
当我尝试复制对象、重新分配 PK ID 并将对象添加到 GeneralInformation 模型时收到错误消息。
我的实体模型中有两个表:
Version
--------
VersionID (PK)
OwnerID
VersionOwner
VersionNumber
还有我的第二张桌子:
GeneralInformation
-------------------
GeneralInformationID (Identity)
VersionID (PK)
FirstName
LastName
如何复制我拥有的 GeneralInformation 对象?
这是我的控制器:
[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.
注意:GeneralInformation 的VersionID 是我要复制的桌子上的PK。
注意:1 to 0..1的Version和GenralInformation有关系
【问题讨论】:
标签: c# asp.net-mvc entity-framework model-view-controller