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 Tuesday, November 24, 2009 11:45 PM

Comments on this post

# re: Entity Framework – Come impostare una relazione

Requesting 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.
Left by Ellennd22 on Jan 25, 2010 6:38 AM

# re: Entity Framework – Come impostare una relazione

Requesting Gravatar...
When you are in uncomfortable position and have got no cash to get out from that, you would need to take the loans. Just because it should aid you unquestionably. I get college loan every single year and feel fine just because of that.
Left by LouMoore20 on Mar 24, 2010 5:26 AM

# re: Entity Framework – Come impostare una relazione

Requesting Gravatar...
To have academic success, some persons have to determine if they are willing to perform the creative writing essay or just buy essay papers online of the best quality.
Left by EricaPollard on Mar 26, 2010 2:50 AM

# re: Entity Framework – Come impostare una relazione

Requesting Gravatar...
The most easy pass way to know about this post is to purchase custom papers and just buy an essay.
Left by KELLYMarla on Mar 26, 2010 8:32 PM

# re: Entity Framework – Come impostare una relazione

Requesting Gravatar...
Skillfully created theme, if only all bloggers allowed the identical significance as you, the internet would be a much preferably locality. And it’s well known that It is not daily grinds that crucify guy, it is worry. Can I approve you a excellent place where you can find narrative essays. Please keep it up! Cheers.
Left by MaddenVALERIE on Mar 30, 2010 1:02 AM

Your comment:

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