0

マスター エンティティと子エンティティを複製する必要があります。仕事をしているように見えるCodeProjectでこのソリューションに出くわしました。 http://www.codeproject.com/Tips/474296/Clone-an-Entity-in-Entity-Framework-4を参照してください。

ただし、このコードは EF4 と EntityObject を使用しているのに対し、私は EF5 と DBContext を使用しているため、どのような変更を加える必要があるのでしょうか?

コードは次のとおりです。

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;

}

呼び出しコードは次のとおりです。

Customer newCustomer = CopyEntity(myObjectContext, myCustomer, false);

foreach(Order order in myCustomer.Orders)
{
Order newOrder = CopyEntity(myObjectContext, order, true);
newCustomer.Orders.Add(newOrder);
}

この投稿に対するフィードバックが活発ではないように見えるので、ここに投稿します。これは、EF のプロなら誰でも答えられる質問だと確信しています。

よろしくお願いします。

4

2 に答える 2

0

あなたのコードは、エンティティのプロパティにある場合にのみ機能しますEdmScalarPropertyAttribute

MetadataWorkspaceまたは、エンティティ プロパティを取得するために使用できます

public static class EntityExtensions
{
    public static TEntity CopyEntity<TEntity>(DbContext context, TEntity entity, bool copyKeys = false)
        where TEntity : class
    {
        ObjectContext ctx = ((IObjectContextAdapter)context).ObjectContext;
        TEntity clone = null;
        if (ctx != null)
        {
            context.Configuration.AutoDetectChangesEnabled = false;
            try
            {
                clone = ctx.CreateObject<TEntity>();
                var objectEntityType = ctx.MetadataWorkspace.GetItems(DataSpace.OSpace).Where(x => x.BuiltInTypeKind == BuiltInTypeKind.EntityType).OfType<EntityType>().Where(x => x.Name == clone.GetType().Name).Single();

                var pis = entity.GetType().GetProperties().Where(t => t.CanWrite);
                foreach (PropertyInfo pi in pis)
                {
                    var key = objectEntityType.KeyProperties.Where(t => t.Name == pi.Name).FirstOrDefault();
                    if (key != null && !copyKeys)
                        continue;
                    pi.SetValue(clone, pi.GetValue(entity, null), null);
                }
            }
            finally
            {
                context.Configuration.AutoDetectChangesEnabled = true;
            }
        }
        return clone;
    }
}
于 2014-09-04T14:43:06.787 に答える