Generic Clone of EF6 Entity

后端 未结 3 1937
没有蜡笔的小新
没有蜡笔的小新 2021-01-27 11:16

I am trying to get a generic CloneEntity function working with EF6.0.2

public static T CopyEntity(MyContext ctx, T entity, 
bool copyKeys = false) where         


        
3条回答
  •  盖世英雄少女心
    2021-01-27 11:30

    public class EntityHelper
    {
        public static T CopyEntity(MCEntities ctx, T entity, bool copyKeys = false) where T : class, new()
        {
            T clone = new T();
            var en = ctx.Entry(clone);
            en.State = System.Data.Entity.EntityState.Added;
            ctx.Entry(clone).CurrentValues.SetValues(entity);
            en.State = System.Data.Entity.EntityState.Detached;
            return clone;
        }
    }
    

提交回复
热议问题