0

I want to do a copy of an object without copying the ID and without doing it field by field.

Is there anyway?

I'm trying to do this way but I have an Exception:

The property 'ID' is part of the object's key information and cannot be modified.

Object o = getObject()

Object h = new Object();
h = o;
h.ID = 0;
db.Object.Add(h);
db.SaveChanges();
Partha
  • 402
  • 4
  • 15
Martina
  • 1,852
  • 8
  • 41
  • 78
  • Possible duplicate: https://stackoverflow.com/questions/2185155/cloning-data-on-entity-framework – lorisleitner Oct 30 '18 at 08:04
  • 1
    You should have a look at AutoMapper – jazb Oct 30 '18 at 08:05
  • AutoMapper would fit for you, this is the basic configuration. https://www.infoworld.com/article/3192900/c-sharp/how-to-work-with-automapper-in-c.html – Phael Oct 30 '18 at 08:09
  • you have to do it field by field, auto mapper does the same on back end and plus it does lot more other things which might not be required in your case. – umer Oct 30 '18 at 11:18

1 Answers1

0

I used AutoMapper like it's suggested

        Object1 o = getObject();
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Object1,Object1>();
        });
        var mapper = config.CreateMapper();

        var h = mapper.Map<Object1>(o);



        h.ID = 0;
        db.Object.Add(h);
        db.SaveChanges();

And it works.

Martina
  • 1,852
  • 8
  • 41
  • 78