1

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?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • You create only one post. What else do you expect ? Yes you can create a second one, or Clone the first one - as you like. `post2 = new Post { Title = post1.Title };` – Holger Nov 12 '19 at 16:33
  • marking this is a duplicate seems a little aggressive. Plus my full answer below gives you an EF model clone in 1/100th of the code of the accepted answer that has been linked as duplicated – Mike Marshall Nov 12 '19 at 20:45

2 Answers2

4

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();
Mike Marshall
  • 7,788
  • 4
  • 39
  • 63
  • Sure, but I would like to avoid that as Post has many properties not only the two ones that I mentioned. So I was looking for a better way to clone it. – Miguel Moura Nov 12 '19 at 16:36
  • See my edit, I found another answer on SO with code to do a deep copy using EF models – Mike Marshall Nov 12 '19 at 16:57
  • Worked! Copy all object members/properties using: Post post2 = (Post) context.Entry(post1).CurrentValues.ToObject(); Faster when using await context.SaveChangesAsync(); – Brian Bird Jan 25 '23 at 18:47
0

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

Dongdong
  • 2,208
  • 19
  • 28