refresh
refresh

Reputation: 1329

Duplicate entity object without its Id

I have to duplicate an entity but not its Id and then treat the new entity as a separate object. The set accessor of my entities Id are not accessible. So I can't modify the Id and set it to null, and right now I am only allowed to do AddOrUpdate (based on the Id) in the db. I cannot do a simple Add. I need to be able to duplicate or clone different entities, so maybe a generic function will help me to do that, but I am lost about where to start. Any help pls.?

Upvotes: 0

Views: 837

Answers (1)

Steve Py
Steve Py

Reputation: 34698

One option is to leverage Automapper to perform the shallow clone. Automapper can be configured to ignore specific properties such as the ID, or all properties with inaccessible setters:

So given an entity like:

public class SomeObject
{
    public int SomeId { get; private set; }
    public string Name { get; set; }

    public SomeObject(int? id = null)
    {
        if (id.HasValue)
            SomeId = id.Value;
    }
}

you can configure a mapper like so:

        var mapperConfig = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<SomeObject, SomeObject>().IgnoreAllPropertiesWithAnInaccessibleSetter();
        });
        IMapper mapper = new Mapper(mapperConfig);

        var test = new SomeObject(1) { Name = "Fred" }; // object we will clone.
        var test2 = new SomeObject(); // example of an existing "new" object to copy values into...
        mapper.Map(test, test2); // Copy values from first into 2nd..
        var test3 = mapper.Map<SomeObject>(test); // Example of letting automapper create a new clone.

In both cases the ID column was not copied over. You may want to use the "test2" example to utilize context.Entities.Create to create a new tracking proxy for the new entity, though EF works fine with newed up POCO instances of the entity provided it is added to the Entities DbSet.

Upvotes: 2

Related Questions