开发者

cloning an object with entity framework 4

开发者 https://www.devze.com 2023-01-24 18:42 出处:网络
I found the following code that is supposed to clone an entity.In my case I have a table for a person and there are multiple verticals for phone numbers, emails, etc.When I try to clone a person entit

I found the following code that is supposed to clone an entity. In my case I have a table for a person and there are multiple verticals for phone numbers, emails, etc. When I try to clone a person entity the code appears to work fine. However, when I try to add the object to my table I get the following error.

"The object could not be added or attached because its EntityReference has an EntityKey property value that does not match the EntityKey for this object."

I'm not quite sure what to change to make this work.

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;
        }

Here's how I'm using the code.

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;
        }


When you clone the object, the EntityKey property is probably still set. Try setting newcand.EntityKey = null directly after cloning.

0

精彩评论

暂无评论...
验证码 换一张
取 消