Miguel Moura
Miguel Moura

Reputation: 39484

Clone an object (EF entity) in C#

Using C# 8 e ASP.NET Core I have the following:

  Context context = new Context();

  Post post1 = new Post {
    Enabled = true,
    Title = "Some title"
  };

  Post post2 = post1;
  post2.Enabled = false;

  context.Posts.Add(post1);
  context.Posts.Add(post2);

On context, which is an EF DBContext, I get only one post (post2);

Maybe I am wrong but I think I should Copy / Clone post1 to define post2.

Am I right? How to do this?

Upvotes: 1

Views: 2461

Answers (2)

Mike Marshall
Mike Marshall

Reputation: 7850

because of this line:

Post post2 = post1;

post1 and post2 are the same object, and EF will treat them as the same object.

You should have some clone to create a totally new post, like:

Post post2 = new Post()
{
   Title = post1.Title,
   Enabled = false;
};

Possible other way to clone without setting individual properties (see this answer for more detail)

Post post2 = (Post) context.Entry(post1).CurrentValues.ToObject();

Upvotes: 5

Dongdong
Dongdong

Reputation: 2508

since class is ReferenceType, so you only get a post2 with Enabled as false, which is actually post1, they are same thing by your code, post1 === post2.

I believe your real class contains more properties than example. so if you want to a simple Clone, you can use var post2 = (Post)post1.Clone();, but normaly we make deep clone in complex objects, you can follow this post: Deep cloning objects

Upvotes: 0

Related Questions