Clone an object (EF entity) in C#

asp.net-core asp.net-core-3.0 c# c#-8.0 entity-framework-core

Question

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?

1
0
11/12/2019 4:27:26 PM

Accepted Answer

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();
2
11/12/2019 4:57:29 PM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow