Set entity as new

Posts   
 
    
cerberis
User
Posts: 93
Joined: 20-May-2011
# Posted on: 20-Jan-2015 09:15:58   

Hello,

what is the best way to clone record in database using entities? As I understand we need to set new primary key (guid), set IsNew field to true and mark non primary key fields as IsChanged.

Is this enough? Maybe there is some other better way? The idea that we need to load entity with childs, make a clone of it and insert as new.

regards Mantas

Walaa avatar
Walaa
Support Team
Posts: 14950
Joined: 21-Aug-2005
# Posted on: 20-Jan-2015 17:50:37   

Please check the answer in the following thread: https://www.llblgen.com/tinyforum/Messages.aspx?ThreadID=22290

cerberis
User
Posts: 93
Joined: 20-May-2011
# Posted on: 21-Jan-2015 07:51:08   

These answers are known to me. However I would like to mark entity as new without creating another object. Deep cloning is not an option because we do not want to make new complete graph, but only selected childs.

I have such a code which seems like working, however would like to ask if this code does not have some side effects on object?


        public static void SetAsNew(this IEntity2 entity)
        {
            entity.IsDirty = true;
            entity.IsNew = true;
            entity.Fields.IsDirty = true;
            foreach (var field in entity.Fields)
            {
                if (!field.IsPrimaryKey)
                {
                    if (!field.IsNullable || (field.IsNullable && !field.IsNull))
                    {
                        field.IsChanged = true;
                    }
                }
            }
            if (entity.PrimaryKeyFields.Count == 1 && entity.PrimaryKeyFields[0].DataType == typeof(Guid))
            {
               IEntityField2 field = entity.PrimaryKeyFields[0];
               field.CurrentValue = Guid.NewGuid();
               field.IsChanged = true;
            }
        }

Walaa avatar
Walaa
Support Team
Posts: 14950
Joined: 21-Aug-2005
# Posted on: 22-Jan-2015 04:28:40   

The code seems fine with respect to making a single entity as new.