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();

posted @ Tuesday, November 24, 2009 11:45 PM

Print

Comments on this entry:

# re: Entity Framework – Come impostare una relazione

Left by Ellennd22 at 1/25/2010 6:38 AM
Gravatar
The thesis proposal could be needed by some scholars if contain the issue close to this good topic. I opine the it is come-at-able to find the dissertation writing service which can perform that issue.

Your comment:



 (will not be displayed)


 
 
 
Please add 5 and 5 and type the answer here:
 

Live Comment Preview:

 
«March»
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910