在我的mvc4 Web应用程序中,我必须将之前保存的一个表单的所有数据复制到另一个新创建的表单中。但是当我使用以下代码复制数据时,所有数据都从一种形式移动到另一种形式,并删除前一种形式的数据。请说明原因以及如何复制数据。
print
答案 0 :(得分:0)
我通过多次调试代码得到了这个问题的解决方案。这里发生的事情是当我将子表数据复制到新表格时
newForm.QmsEvaluationFormControls = copyData.FormControls;
和newForm.QmsEvaluationParameters = copyData.FormParameters;
每行的外键更改为新表单的主键。 现在,当我通过以下方法复制数据时,每件事情都正常 -
public FormEntity CopyFormData(CopyForm copyForm)
{
using (SIPSEntities db = new SIPSEntities())
{
if (db.QmsEvaluationForms.Where(x => x.IsActive == true).Any(x => x.FormName == copyForm.FormName))
{
throw new Exception("Form Name Already Exists!");
}
else
{
var copyData = (from log in db.QmsEvaluationForms
where log.EvaluationFormId == copyForm.CopyFrom && log.IsActive == true
select log).FirstOrDefault();
//Insert new form
List<QmsEvaluationFormControl> cloneFormControlList = (from log1 in copyData.QmsEvaluationFormControls where log1.IsActive==true select log1).ToList();
List<QmsEvaluationParameter> clonePaameterList = (from log1 in copyData.QmsEvaluationParameters where log1.IsActive == true select log1).ToList();
QmsEvaluationForm newForm = new QmsEvaluationForm();
newForm.FormName = copyForm.FormName;
newForm.MakeScoreZeroOnFatal = copyData.MakeScoreZeroOnFatal;
newForm.IsActive = true;
newForm.CreatedOn = DateTime.Now;
newForm.SubprocessId = copyForm.SubProcessId;
foreach(var control in cloneFormControlList){
QmsEvaluationFormControl controlData=new QmsEvaluationFormControl();
controlData.Caption=control.Caption;
controlData.CreatedOn=DateTime.Now;
controlData.FieldTypeId=control.FieldTypeId;
controlData.FormValidationParameterId=control.FormValidationParameterId;
controlData.ListNameId=control.ListNameId;
controlData.IsMandatory=control.IsMandatory;
controlData.MaxSize=control.MaxSize;
controlData.IsActive=control.IsActive;
newForm.QmsEvaluationFormControls.Add(controlData);
}
foreach (var parameter in clonePaameterList)
{
QmsEvaluationParameter parameterData = new QmsEvaluationParameter();
parameterData.Category = parameter.Category;
parameterData.ParameteerCode = parameter.ParameteerCode;
parameterData.EvaluationParameter = parameter.EvaluationParameter;
parameterData.ListNameId = parameter.ListNameId;
parameterData.CriticalTypeId = parameter.CriticalTypeId;
parameterData.Weightage = parameter.Weightage;
parameterData.IsActive = parameter.IsActive;
parameterData.CreatedOn = DateTime.Now;
newForm.QmsEvaluationParameters.Add(parameterData);
}
db.QmsEvaluationForms.Add(newForm);
db.SaveChanges();
return new FormEntity { FormId = newForm.EvaluationFormId, FormName = newForm.FormName, MakeZero = newForm.MakeScoreZeroOnFatal };
}
}
}