Entity Framework #3–my scattered notes

When using Entity Framework 4.x Code First you can put your validation code in Data Annotations or inside the DbContext class (this is my preferred mode).

It’s possible to override the virtual method ValidateEntity exposed by the DbContext class and then define your own validation logic in one place.

This method is called once for each distinct entity being modified in your context, and it provides an opportunity for developers to stop the entity update process when some properties are in invalid state.

Here’s an example:

This code will be invoked only if the “ValidateOnSaveEnabled” property of the class DbContextConfiguration is set to true.

Entity Framework #2–my scattered notes Part 2

This is my second post about my Entity Framework Code First usage experience. You can find my first post here.

The Entity Framework Power Tool is a must-have tool for those who use EF in Code First mode, especially with fluent API. With this tool you can reverse-engineering an existing data source and then generate both domain classes (POCO) and the mapping configuration files. The latter are generated by creating a class which inherits from EntityConfiguration<T>, where T is your domain entity type. The tools is able to understand all the existing relations in the database and to transform them in the correct relation mapping in code.

Entity Framework #2–my scattered notes Part 1

Here are a few scattered notes on the use of Entity Framework 4.2 Code First:

  • The core EF Api is contained in the System.Data.Entity.dll assembly
  • The DbContext Object is a lightweight version of the ObjectContext object, the former provides more functionality than the first. If you need to get an ObjectContext instance starting from a DbContext instance you can use the IObjectContextAdapter interface for casting, as shown in the following example:
(myDbContext as IObjectContextAdapter).ObjectContext;
  • The DbSet class is just a wrapper around the ObjectSet class
  • A Complex Type has some limitations, the main are: a) it can expose only properties with primitive types b) it cannot be exposed as a multi-instance (collection)
  • The EntityTypeConfiguration<T> class has an interesting method called WillCascadeOnDelete(bool), whose name makes the idea of the action it takes. Invoking this method with true parameter allows dependent data to be automatically deleted when main data is deleted, but you must pay attention to some aspects: a) it doesn’t work with optional relations but only with required relations b) The dependent data must be explicitly loaded into the context by invoking the “Include” extension method. If you don’t, there are no dependent data in memory and therefore no data will be deleted on database
  • Table splitting requirements: a) entities must have a 1 to 1 relation b) entities must share a common key
  • How a particular class is part of the EF context ? a) Because the context as a property DbSet<T> which reference that class b) Because the class is referenced by another class already tracked by the context c) Because you just inserted a configuration for that class and added to the model builder
  • EF supports three mapping inheritance typologies a) TPH (table per hierarchy) => a base type and all its inherited types are mapped to a single database table with a discriminator column b) TPT (table per type) => There are distinct tables for base type and all its derived types. The tables for derived types contain only the additional fields exposed, while the common fields are mapped to the base type’s table c) TPC (table per concrete type), very similar to TPT. The only difference is that all derived type’s fields are stored in separate tables and not only the common ones. For guidance on which typology to choose depending on various scenarios, you can see this link
  • EF Code First is based on conventions. Conventions are assumptions that can save developers from a lot of work when you define the mapping between domain classes and tables. For example, a convention states that the Id property of a class is also the primary key for that class. Conventions can be singly removed by code, as shown here:

Entity Framework #1 –How to get the original type of an entity when dynamic proxy is enabled

If your Entity Framework context is proxy-enabled, the runtime will create a proxy instance of your entities, i.e. a dynamically generated class which inherits from your entity class and overrides its virtual properties by inserting specific code useful for example for tracking changes and lazy loading.

The proxy instance has a dynamically generated name by the runtime that looks like this:

{System.Data.Entity.DynamicProxies User_00394CF1F92740F13E3EDBE858B6D599DFAF87AA5A089245977F61A32C75AA22}

(User is the original entity class name which the proxy class inherited from).

Starting from the proxy type, if you need to know the original type you have to use the static method GetObjectType of ObjectContext type, as shown in this example:

var userType = ObjectContext.GetObjectType(user.GetType());

Through the FullName property of the type returned by this method you can get the full name of the original type (User in this example)

Visual Basic Tips & Tricks Community Day a Milano

Ieri pomeriggio ho partecipato al Visual Basic Tips & Tricks Community Day tenutosi a Milano.

Devo dire che è stato un pomeriggio decisamente interessante dal punto di vista tecnologico, permettendomi di focalizzare alcuni concetti su tecnologie che uso o che vorrei usare, e mi riferisco a TFS 2010 ed Entity Framework 4.0

L’evento si apre con una sessione di Lorenzo Barbieri che parla delle varie versioni di Visual Studio 2010 che saranno disponibili a breve e delle novità, veramente tante, della nuova versione dell’IDE.

In ordine sparso:

  1. Possibilità di effettuare ricerche parziali con l’Intellisense;
  2. Intellisense nei file Javascript migliorato, ora vengono risolti anche i simboli presenti nei files inclusi, e non solo quelli del file in debugging;
  3. Funzionalità di “search a you type”, per intenderci tipo Google quando ci presenta i risultati della ricerca mano a mano che scriviamo il testo da ricercare;
  4. Funzionalità di “Call Hierarchy”, per il momento presente solo con il linguaggio C#, ovvero la possibilità di navigare a partire da un metodo / proprietà / costruttore verso il codice chiamante / chiamato a partire dal punto di navigazione scelto;
  5. Modalità “Web only” dell’IDE, ovvero la possibilità di utilizzare un IDE con il solo codice in primo piano e tutte le finestre di dialogo minimizzate;
  6. Selezione del testo per colonne;
  7. Gestione degli add-in con un apposito Extention Manager dedicato;
  8. Intellitrace (feature molto molto utile ed interessante per troubleshooting), ovvero un componente capace di registrare tutto quello che avviene nel codice quando questo è in esecuzione, una specie di scatola nera dell’applicazione, utilizzabile su applicazioni scritte con la versione 2.0 del Framework in poi ;
  9. Test di automazione della UI;

Poi è stata la volta di Alessandro Del Sole, che ha mostrato le novità di Team Foundation Server 2010 in ottica singolo sviluppatore o piccoli gruppi di lavoro.

Successivamente Antonio Catucci ha mostrato le novità di Entity Framework 4.0, ovvero:

  • Possibilità di gestione della Foreign Key nel modello dati, senza che la stessa sia nascosta (come è noto nel mondo dei database relazionali una relazione tra 2 tabelle si traduce con la presenza di una colonna in comune tra le due tabelle, che costituisce appunto la relazione, nel mondo OOP una relazione di questo tipo si traduce con la presenza di una proprietà tipizzata nell’oggetto “padre”);
  • Lazy Loading” attivo sempre di default;
  • Pluralization” dell’Entity Set basato sulla grammatica inglese. Con Entity Framework 1.0 questa mancanza mi ha provocato qualche problema, in quanto va gestito a manina;
  • Model-First Design”, feature decisamente interessante che consente di creare un domain model senza che sia necessariamente presente un database da cui partire. Con la versione 1.0 il domain model è forzatamente creato a partire da una base dati esistente;
  • T4 Code Generation”. Con questa feature il codice generato da Entity Framework può essere basato su template, fornendo quindi la possibilità di generazione personalizzata dello stesso.
  • POCO Entity (Plain Old CLR Objects)”, anche questa è una feature molto interessante, ovvero la possibilità di usare nel Domain Model della classi “pulite”, magari già esistenti senza che debbano per forza di cose ereditare da una classe specifica di Entity Framework;
  • Gestiona automatica delle relazioni molti a molti, senza la visualizzazione della terza tabella di legame tra le due relazionate;
  • Nuovo controllo EntityDataSource per il binding dei dati in ASP .NET.
  • Metodo “ApplyCurrentValues”. Permette di gestire le modifiche apportate su oggetti “detached”, ovvero al di fuori dell’ObjectContext attivo, e di propagare le stesse modifiche sull’oggetto avente la stessa chiave presente nell’ObjectContext (oggetto “attached”).
    Come è evidente la versione 4.0 di Entity Framework contiene una pletora di novità, che sicuramente consentiranno a questo ORM made in Microsoft di superare alcuni limiti di “gioventù” della precedente versione.

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:

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: