Copy Entity Framework Object

前端 未结 5 1794
面向向阳花
面向向阳花 2021-01-31 21:52

I have a EF4.1 class X and I want to make copy of that plus all its child records. X.Y and X.Y.Z

Now if I do the following it returns error.

The property \'X.ID\

5条回答
  •  情歌与酒
    2021-01-31 22:22

    In entity-framework-5, this is insanely easy with the DbExtensions.AsNotracking().

    Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext.

    This appears to be the case for all objects in the object graph.

    You just have to really understand your graph and what you do and don't want inserted/duplicated into the DB.

    Lets assume we have objects like:

    public class Person
    {
      public int ID { get; set; }
      public string Name { get; set; }
      public virtual ICollection
    Addresses { get; set; } } public class Address { public int ID { get; set; } public AddressLine { get; set; } public int StateID { get; set; } public ICollection { get; set; } }

    So in order to Duplicate a person, I need to duplicate the addresses, but I don't want to duplicate the States.

    var person = this._context.Persons
      .Include(i => i.Addresses)
      .AsNoTracking()
      .First();
    
    // if this is a Guid, just do Guid.NewGuid();
    // setting IDs to zero(0) assume the database is using an Identity Column
    person.ID = 0;
    
    foreach (var address in person.Addresses)
    {
      address.ID = 0;
    }
    
    this._context.Persons.Add(person);
    this._context.SaveChanges();
    

    If you then wanted to then reuse those same objects again to insert a third duplicate, you'd either run the query again (with AsNoTracking()) or detach the objects (example):

    dbContext.Entry(person).State = EntityState.Detached;
    person.ID = 0;
    foreach (var address in person.Addresses)
    {
      dbContext.Entry(address).State = EntityState.Detached;
      address.ID = 0;
    }
    
    this._context.Persons.Add(person);
    this._context.SaveChanges();
    

提交回复
热议问题