2

I have MVC3 project where I use Entity Framework I have entity with player that user should be able to make copy of.

To make a copy of player I have the following in my repository:

public Player CreateTemplate(Player player)
    {
        var copy = new Player();

        copy.Birth_Date = player.birth_Date;
        copy.Comment = player.Comment;
        copy.Name = player.Name;
        copy.Agent = player.Agent;
        copy.AgentId = player.AgentId;
        foreach (SelectedTeams selectedTeams in player.SelectedTeams.ToList())
        {
            var copyselectedteams = new SelectedTeams();
            copyselectedteams = selectedTeams;
            copy.SelectedTeams.Add(copyselectedteams);
        }
        db.AddToPlayer(copy);
        db.SaveChanges();
        return copy;
    }

The problem for me is, that once my foreach starts looping, my original player lose it's SelectedTeams Is there any solutions is for this problem?

Thanks in advance

2

2 Answers 2

1

Do You have Lazy Loading disabled by any chance? You may try to eager load entity like this:

var firstPlayer = dbContext.Players.Include("SelectedTeams").FirstOrDefault<Player>(p => p.PlayerId == 1);
var copiedPlayer = repo.CreateTemplate(firstPlayer);

Also You shouldn't copy references of existing entities to new entity.

copyselectedteams = selectedTeams;

Instead copy its properties (except relationship keys of course or You will get exceptions).

Sign up to request clarification or add additional context in comments.

Comments

1

You are overwriting the reference to the new object you just created:

var copyselectedteams = new SelectedTeams(); //overwritten...
copyselectedteams = selectedTeams; //...here

1 Comment

Could you give an example on how to not overwrite and instead pass the reference to the new object so the original object wont get affected by the override

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.