zoukankan      html  css  js  c++  java
  • 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);
    
                    
                }
            }
  • 相关阅读:
    设计模式学习--Singleton
    Add Binary
    简洁的ios小界面
    第一节、介绍
    魅族MX5和努比亚布拉格手机參数对照
    python 深浅拷贝 进阶
    为什么要重写equals()方法与hashCode()方法
    在Myeclipse buildpath 加server lib
    push本地代码到github出错
    mysql事务,select for update,及数据的一致性处理
  • 原文地址:https://www.cnblogs.com/perock/p/3640797.html
Copyright © 2011-2022 走看看