Copy Entity Record

public static T CopyEntity<T>(NorthwindEntities ctx, T entity, bool copyKeys = false) where T : EntityObject
        {
            T clone = ctx.CreateObject<T>();
            PropertyInfo[] pis = entity.GetType().GetProperties();

            foreach (PropertyInfo pi in pis)
            {
                EdmScalarPropertyAttribute[] attrs = (EdmScalarPropertyAttribute[])pi.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false);

                foreach (EdmScalarPropertyAttribute attr in attrs)
                {
                    if (!copyKeys && attr.EntityKeyProperty)
                        continue;

                    pi.SetValue(clone, pi.GetValue(entity, null), null);
                }
            }

            return clone;
        }

 

 

How to using ?

private void btnCopyNew_Click(object sender, EventArgs e)
        {
            Customer cust = customerBindingSource.Current as Customer;
            if (cust != null)
            {
                //context.Detach(cust);
                Customer customerCopy = CopyEntity<Customer>(context,cust);
                Random rd = new Random();
                string id = rd.Next(10000, 99999).ToString();
                customerCopy.CustomerID = id;

                context.Customers.AddObject(customerCopy);
                //context.ObjectStateManager.ChangeObjectState(cust, EntityState.Added);
                
                //context.Refresh(System.Data.Objects.RefreshMode.StoreWins, cust);
                context.SaveChanges();

                //customerBindingSource.DataSource = context.Customers.Execute(System.Data.Objects.MergeOption.AppendOnly);
                customerBindingSource.ResetBindings(false);

                gridView1.FocusedRowHandle = gridView1.LocateByValue("CustomerID", id);

                
            }
        }

 

posted @ 2014-04-02 15:25  perock  阅读(374)  评论(0编辑  收藏  举报