Entity Framework – Come impostare una relazione

Con Entity Framework è possibile referenziare tra loro entità  in modo molto semplice.

Supponendo di avere l'entità  Customer e l'entità Category, che rappresentano rispettivamente un cliente e la sua categoria di appartenenza, nel data model l'oggetto Customer conterrà  una proprietà  chiamata Category di tipo Category.

In fase di creazione di un nuovo oggetto Customer è necessario associare la Category di appartenenza scelta dall'utente, molto probabilmente mediante una dropdown list contenente la lista delle categorie (DataTextField), e l'Id delle stesse (DataValueField).

Istintivamente, verrebbe di fare una cosa di questo tipo:

   1: CustomerEntity customerEntity = new CustomerEntity();
   2: customer.Category = new Category() {Id=1, Description="New Category"};
   3: customerEntity.AddToCustomer(customer);
   4: customerEntity.SaveChanges();

che però non funziona in quanto solleva una eccezione del tipo "An entity object cannot be referenced by multiple instances of IEntityChangeTracker".

Per poter funzionare la reference ha bisogno esclusivamente dell'Id della Categoria di appartenenza del Cliente, e non dell'intero oggetto Category, anche perchè per ricrearlo interamente potrebbe essere necessario accedere al database di memorizzazione.

Occorre semplicemente creare un oggetto EntityKey ed associarlo all'oggetto Customer corrispondente, in questo modo:

 

   1: int idCategory  = 1; // in un caso reale è letto da un controllo della pagina web
   2: CustomerEntity customerEntity = new CustomerEntity();
   3: IEnumerable<KeyValuePair<string, object>> entityKeyValues =
   4:     new KeyValuePair<string, object>[] {
   5:     new KeyValuePair<string, object>("Id", idCategory) };
   6: EntityKey key = new EntityKey("Entities.Category", entityKeyValues);
   7: customer.CategoryReference.EntityKey = key;
   8: customerEntity.AddToCustomer(customer);
   9: customerEntity.SaveChanges();

Print | posted on Monday, March 15, 2010 6:16 AM

Comments on this post

No comments posted yet.

Your comment:

 (will show your gravatar)
 
Please add 1 and 5 and type the answer here: