Search code examples
asp.net-mvcasp.net-mvc-3entity-frameworklinq-to-entitiesclone

How to Clone the Entity object and all of its associated entities values aswell with EF in MVC


I have a entity "Player" that has "one to many" association to other entities. When I clone one of my Player rows the entities that are associated with Player are not getting cloned. but the Player data row gets cloned. I need the assocations values to get cloned aswell. How can I do this?

Here is the code inside my respository

public Player CreateTemplate(Player player)
{
db.Detach(player);
Player.EntityKey = null;
db.AddToPlayer(player);
db.SaveChanges();
return player;
}

Here is my Action method:

public ActionResult CreatePlayerTemplate(int id)
{
var player = MyRepository.GetPlayerdByID(id);
MyRepository.CreateTemplate(player);
return View();
}

Update: this how i retrieve Player :

 public Player GetPlayerByID(int id)
    {
        return db.Player.SingleOrDefault(x => x.Id == id);
    }

Solution

  • Alternative, kinda hacky approach - use mapping tool, like AutoMapper

    Define self-maps for every entity participating in cloning, and configure to ignore entity key

    Mapper.CreateMap<Player, Player>()
    .ForMember(x => x.EntityKey, y => y.Ignore());
    
    Mapper.CreateMap<SomeOtherEntity, SomeOtherEntity>()
    .ForMember(x => x.EntityKey, y => y.Ignore());
    

    And then just clone entities

    var clonnedPlayer = Mapper.Map<Player>(originalPlayer);
    

    Also, this way you could configure not to clone lookup-like tables to not duplicate lookup data