ps__
ps__

Reputation: 365

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);
    }

Upvotes: 2

Views: 3111

Answers (2)

archil
archil

Reputation: 39501

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

Upvotes: 2

undefined
undefined

Reputation: 34309

You need to also detach all of the associated entities as the detach method above only detaches the player.

You also need to make sure you null the PKs of each of these entitys to ensure you dont perform a duplicate key insert

public Player CreateTemplate(Player player)
{
   db.Detach(player);
   foreach(var thing in player.Things)
   {
      context.Detach(thing);
      thing.EntityKey = null;
   }
   Player.EntityKey = null;
   db.AddToPlayer(player);
   db.SaveChanges();
   return player;
}

Upvotes: 2

Related Questions