c# - 使用 Linq 2 Sql 拍摄项目的快照(克隆)

标签 c# linq-to-sql cloning

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

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

例如

var projectEntity = getProjectEntity(projectId);

draftProjectEntity = projectEntity
draftProjectEntity.Status = NewStatus

context.SubmitChanges();

我找到了这个链接 from Marc Gravell

这是其中的一部分,但它会将子记录更新到新的 draftProject,我需要将其复制到那里。

最佳答案

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

There are ways of doing this with Reflection - 如果您要经常这样做 - 那么我强烈建议您研究一下这种方法。

但是,如果您只深入一个级别,或者只针对一小部分对象图,那么可能值得简单地手动完成并在您的实体上实现您自己的 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 接口(interface)的信息...请查看此线程:Should I provide a deep clone when implementing ICloneable?

关于c# - 使用 Linq 2 Sql 拍摄项目的快照(克隆),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2695447/

相关文章:

c# - 如何从本地存储的文件中读取 JSON?

c# - 名为 'System' 的表的 LINQ to SQL 问题

reference - 为什么克隆我的自定义类型会导致 &T 而不是 T?

.net - 反序列化和空引用最佳实践 - 设置为空还是忽略?

c# - 创建具有 native 依赖项的 NetCore NuGet 包

c# - .Net 多个客户端和中央服务器之间的数据同步

c# - 帮助处理两个表的 linq 查询

java - 关于新对象

c# - 尝试将外部网页加载到框架/对话框中

c# - 如何将 linq var 数据类型传递给方法?