MVC实体模型复制对象

时间:2014-10-15 18:23:46

标签: c# asp.net-mvc entity-framework asp.net-mvc-3 entity-framework-4

我有一个名为GeneralInformation的对象,我想在我的表格中复制,但是,显然这条新记录会有不同的GeneralInformationID

我的目标是让用户点击一个链接到domain.com/proforma/copyversion/<id>,从下面我的控制器执行操作。

这是我的控制器:

[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");
}

我收到错误消息:"Cannot convert source type 'null' to target type 'int'GeneralInformationID是主键和标识,自动生成列。

我的实体模型中有两个表:

GeneralInformation
-------------------
GeneralInformationID (PK)
VersionID
FirstName
LastName

我的第二张桌子:

Version
--------
VersionID (PK)
OwnerID
VersionOwner
VersionNumber
isLocked

如何制作我拥有的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 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");
}

我收到以下错误:

The property 'VersionID' is part of the object's key information and cannot be modified.

VersionID是桌面上的PK。

1 个答案:

答案 0 :(得分:0)

在您的行动中执行此操作:

GeneralInformation generalInformationCopy = db.GeneralInformations.Create(); // i assume that you have this dbset in your contex
db.GeneralInformations.Add(generalInformationCopy);     
db.Entry<GeneralInformation>(generalInformationCopy).CurrentValues.SetValues(generalInformation);
db.SaveChanges();

或阅读this,了解克隆实体。