我找到了以下代码来克隆实体。在我的情况下,我有一个人的表,电话号码,电子邮件等有多个垂直。当我尝试克隆一个人实体时,代码似乎工作正常。但是,当我尝试将对象添加到我的表时,我得到以下错误。
“无法添加或附加对象,因为其EntityReference的EntityKey属性值与此对象的EntityKey不匹配。”
我不太清楚要改变什么才能使这项工作。
private static T DataContractSerialization<T>(T obj)
{
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
T newObject = (T)dcSer.ReadObject(memoryStream);
return newObject;
}
以下是我使用代码的方式。
public static void CopyData(int sourcecompanyid)
{
var rUtil = new CREntities();
rUtil.Connection.Open();
using (var r = new CREntities())
{
var candidates = r.Candidates.Include("Phones").Include("Emails").Where(c => c.companyId == sourcecompanyid);
foreach (var candidate in candidates)
{
ObjectParameter newcandid = new ObjectParameter("newcandid", typeof(string));
Candidate newcand = DataContractSerialization<Candidate>(candidate);
rUtil.GetNextCandId(newcandid);
newcand.CandID = newcandid.Value.ToString();
foreach (var phone in newcand.Phones)
phone.CandID = newcand.CandID;
foreach (var email in newcand.Emails)
email.CandID = newcand.CandID;
rUtil.Candidates.AddObject(newcand);
rUtil.SaveChanges();
}
}
rUtil.Connection.Close();
rUtil.Dispose();
}
private static T DataContractSerialization<T>(T obj)
{
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
T newObject = (T)dcSer.ReadObject(memoryStream);
return newObject;
}
答案 0 :(得分:0)
克隆对象时,可能仍设置了EntityKey属性。尝试克隆后直接设置newcand.EntityKey = null。