Entity Framework 6: Clone object except ID

前端 未结 5 1087
旧时难觅i
旧时难觅i 2020-12-01 04:48

In my MVVM program I have a Model class (say MyModel) from which I have an instance of reading from the database (using Entity Framework). When retrieving the o

5条回答
  •  不知归路
    2020-12-01 05:29

    Lori Peterson has suggested using .AsNoTracking() to perform cloning in EF6. I'm using this method and can confirm that it works. You can even include child objects.

    var entity = context.Entities
                        .AsNoTracking()
                        .Include(x => x.ChildEntities)
                        .FirstOrDefault(x => x.EntityId == entityId);
    
    entity.SomeProperty = DateTime.Now;
    
    context.Entities.Add(entity);
    context.SaveChanges();
    

    When you are retrieving an entity or entities from a dataset, you can tell Entity Framework not to track any of the changes that you are making to that object and then add that entity as a new entity to the dataset. With using .AsNoTracking, the context doesn’t know anything about the existing entity.

提交回复
热议问题