Duplicate LINQ to SQL entity / record?

前端 未结 5 1004
傲寒
傲寒 2021-01-02 02:35

What would be considered the best practice in duplicating [cloning] a LINQ to SQL entity resulting in a new record in the database?

The context is that I wish to mak

5条回答
  •  醉酒成梦
    2021-01-02 02:59

    Create a new instance and then use the linq mapping classes together with reflection to copy member values.

    E.g.

    public static void CopyDataMembers(this DataContext dc,
                                       object sourceEntity,
                                       object targetEntity)
    {
        //get entity members
        IEnumerable dataMembers = 
             from mem in dc.Mapping.GetTable(sourceEntity.GetType())
                                     .RowType.DataMembers
             where mem.IsAssociation == false
             select mem;
    
        //go through the list of members and compare values
        foreach (MetaDataMember mem in dataMembers)
        {
           object originalValue = mem.StorageAccessor.GetBoxedValue(targetEntity);
           object newValue = mem.StorageAccessor.GetBoxedValue(sourceEntity);
    
            //check if the value has changed
            if (newValue == null && originalValue != null 
                || newValue != null && !newValue.Equals(originalValue))
            {
                //use reflection to update the target
                System.Reflection.PropertyInfo propInfo = 
                    targetEntity.GetType().GetProperty(mem.Name);
    
                propInfo.SetValue(targetEntity, 
                                  propInfo.GetValue(sourceEntity, null), 
                                  null);
    
                // setboxedvalue bypasses change tracking - otherwise 
                // mem.StorageAccessor.SetBoxedValue(ref targetEntity, newValue);
                // could be used instead of reflection
            }
        }
    }
    

    ...or you can clone it using the DataContractSerializer:

    internal static T CloneEntity(T originalEntity) where T : someentitybaseclass
    {
        Type entityType = typeof(T);
    
        DataContractSerializer ser =
            new DataContractSerializer(entityType);
    
        using (MemoryStream ms = new MemoryStream())
        {
            ser.WriteObject(ms, originalEntity);
            ms.Position = 0;
            return (T)ser.ReadObject(ms);
        }
    }
    

提交回复
热议问题