2010-07-23 4 views
5

Voglio creare una copia il mio scopo nel mio DB con l'utilizzo di Entity FrameworkCome aggiungere un'entità esistente come una nuova entità con Entity Framework

prima ho ottenuto il mio "Libro" da DB

var entity1 = new testEntities(); 
var book= entity1.Books.First(); 
entity1.Dispose(); 

poi, ho cercato di aggiungere questo oggetto come un nuovo oggetto

var entity2 = new testEntities(); 
book.Id = 0; 
entity2.SaveChanges(); 
entity2.Dispose(); 

anche io TrID a initilize EntityKey del libro non ha funzionato

C'è un modo per farlo senza creare un nuovo libro e copiare le proprietà dal precedente?

Grazie

risposta

6

È necessario prendere l'entità, modificare il EntityState al Added nel ObjectStateManager e chiamare SaveChanges:

var entity1 = new testEntities(); 
var book = entity1.Books.First(); 

ObjectStateEntry bookEntry = entity1.ObjectStateManager.GetObjectStateEntry(book); 
bookEntry.ChangeState(EntityState.Added); 

entity1.SaveChanges(); 

Questo copierà la vostra 'libro'.

Problemi correlati