I am trying to get a generic CloneEntity function working with EF6.0.2
public static T CopyEntity<T>(MyContext 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;
}
[update] I had to change the declaration to
public static T CloneEntity<T>(T entity, bool copyKeys = false) where T : class
This solved a compile error : 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method
However when I use this method no properties are copied to the new object.
I aren't using code first. The object I am using with it has been generated from the edmx file.
The kind of object I am using it with is generated from T4
public partial class job
{
public short LineID { get; set; }
public short CycleID { get; set; }
// other fields
}
My DBContext is like
public partial class DataEntities : DbContext
{
public DbSet<job> Jobs { get; set; }
}
[Update]
I tried
using (var db = CreateDb())
{
var nJob = new job();
db.jobs.Attach(nJob);
db.Entry(nJob).CurrentValues.SetValues(job);
return nJob;
}
but I get an error
"The property 'JobID' is part of the object's key information and cannot be modified. "
The context is a partial class
there is also
partial class DataEntities
{
public DataEntities(string efConnectString)
: base(efConnectString)
{
}
}