2

我有一个带有多个子表的项目实体,例如 ProjectAwards ProjectTeamMember

我想将项目(和子表)中的数据复制到新的项目记录中并更新项目状态。

例如

var projectEntity = getProjectEntity(projectId);

draftProjectEntity = projectEntity
draftProjectEntity.Status = NewStatus

context.SubmitChanges();

我从 Marc Gravell找到了这个链接

它是其中的一部分,但它将子记录更新到新的草稿项目,我需要它复制。

4

1 回答 1

1

不幸的是,您在这里所做的是将变量设置draftProjectEntity为对projectEntity对象的引用。也就是说,它们现在指向同一个对象。您需要做的projectEntity.

有很多方法可以使用反射来做到这一点——如果你要经常这样做——那么我强烈建议你研究这种方法。

但是,如果您只深入一个级别,或者只针对一小部分对象图,那么可能值得简单地手动完成并在您的实体上实现您自己的 IDeepCloneable ......

public interface IDeepCloneable<T>
{
    T DeepClone();
}

public class Person : IDeepCloneable<Person> 
{
    public string Name { get; set; }
    public IList<Address> Addresses { get; set; }

    public Person DeepClone()
    {
        var clone = new Person() { Name = Name.Clone().ToString() };

        //have to make a clone of each child 
        var addresses = new List<Address>();
        foreach (var address in this.Addresses)
            addresses.Add(address.DeepClone());

        clone.Addresses = addresses;
        return clone;
    }
}

public class Address : IDeepCloneable<Address>
{
    public int StreetNumber { get; set; }
    public string Street { get; set; }
    public string Suburb { get; set; }

    public Address DeepClone()
    {
        var clone = new Address()
                        {
                            Street = this.Street.Clone().ToString(),
                            StreetNumber = this.StreetNumber, //value type - no reference held
                            Suburb = this.Suburb.Clone().ToString()
                        };
        return clone;
    }
}

//usage:
var source = personRepository.FetchByName("JoeBlogs1999");
var target = source.DeepClone();

//at this point you could set any statuses, or non cloning related changes to the copy etc..

targetRepository.Add(target);
targetRepository.Update;

有关为什么我不为此使用 ICloneable 接口的信息...请查看此线程:在实现 ICloneable 时我应该提供深度克隆吗?

于 2010-05-12T08:17:18.900 回答