Entity Framework 6: Clone object except ID

前端 未结 5 1084
旧时难觅i
旧时难觅i 2020-12-01 04:48

In my MVVM program I have a Model class (say MyModel) from which I have an instance of reading from the database (using Entity Framework). When retrieving the o

5条回答
  •  生来不讨喜
    2020-12-01 05:34

    I found this looking to see if there was a better way to clone an object than I was currently using and noticed that there is a potential problem with the accepted answer if you are trying to do multiple clones...at least if you want to avoid creating your context many times...

    I don't know if this is the best approach to cloning, which is why I was looking for another way. But, it works. If you need to clone an entity multiple times, you can use JSON serialization to clone...something like this (using Newtonsoft JSON).

    using( var context = new Context() ) {
        Link link    = context.Links.Where(x => x.Id == someId);
        bool isFirst = true;
        foreach( var id in userIds ) {
            if( isFirst ) {
                link.UserId = id;
                isFirst     = false;
            }
            else {
                string cloneString = JsonConvert.SerializeObject(link);
                Link clone = JsonConvert.DeserializeObject(cloneString);
                clone.UserId = id;
                context.Links.Add(clone);
            }
        }
        context.SaveChanges();
    }
    

提交回复
热议问题