This is a general extension method that allows you to generate cloning.
You need to extract System.Linq.Dynamic from nuget.
public TEntity Clone<TEntity>(this DbContext context, TEntity entity) where TEntity : class { var keyName = GetKeyName<TEntity>(); var keyValue = context.Entry(entity).Property(keyName).CurrentValue; var keyType = typeof(TEntity).GetProperty(keyName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).PropertyType; var dbSet = context.Set<TEntity>(); var newEntity = dbSet .Where(keyName + " = @0", keyValue) .AsNoTracking() .Single(); context.Entry(newEntity).Property(keyName).CurrentValue = keyType.GetDefault(); context.Add(newEntity); return newEntity; }
The only thing you need to implement is the GetKeyName method. It can be anything from return typeof(TEntity).Name + "Id" to return the first guid property or return the first property marked with DatabaseGenerated(DatabaseGeneratedOption.Identity)] .
In my case, I already tagged my classes [DataServiceKeyAttribute("EntityId")]
private string GetKeyName<TEntity>() where TEntity : class { return ((DataServiceKeyAttribute)typeof(TEntity) .GetCustomAttributes(typeof(DataServiceKeyAttribute), true).First()) .KeyNames.Single(); }
Jรผrgen Steinblock Oct 27 '15 at 7:01 2015-10-27 07:01
source share