Entity Framework database initialization

Lascia un commento

With version 4.1 or later Entity Framework provides a useful way for recreate and optionally re-seed the database with data the first time or before the execution of unit test.

For this purpose Microsoft provides some classes:

  • CreateDatabaseIfNotExists
  • DropCreateDatabaseAlways
  • DropCreateDatabaseIfModelChanges

All classes implement interface IDatabaseInitializer<T> where T is a DbContext.

For example if you want populate database with base informations before execute
an unit test you can write code like this:

public class MyTestIntializer : DropCreateDatabaseAlways<MyContext>
{
  protected override void Seed( MyContext context )
  {
      var categories = new Lists<Category>();
      var products = new Lists<Product>();

      categories.Add( new Category { Name = "tech" } );
      categories.Add( new Category { Name = "food" } );

      products.Add( new Product { Name = "cpu", Category = categories[0] } );
      products.Add( new Product { Name = "harddisk",
                          Category = categories[0] } );
      products.Add( new Product { Name = "biscuits",
                          Category = categories[1] } );

      addToContext<Category>( context, categories );
      addToContext<Product>( context, products );
  }

  private void addToContext<T>( MyContext context, IList collection )
  {
      foreach( var item in collection )
      {
          context.Set<T>().Add( item );
      }
   }
}

This data initializer drop (if exists) and create database and finally populate it with
categories and products.

Now we can add it to our test class.

[ClassInitialize()]
public static void MyClassInitialize( TestContext testContext )
{
    Database.SetInitializer<MyContext>( new MyTestIntializer() );
}

Autofac Dependency resolution with ASP.NET MVC

Lascia un commento

The current version of ASP.NET MVC (release 3) supports a new IDependencyResolver interface that makes it easier to integrate DI frameworks.

For instance, if you are using AutoFac you can write code like this:

public class AutoFacDependencyResolver : IDependencyResolver
{
   readonly IContainer _container;
   public AutoFacDependencyResolver ( ContainerBuilder builder )
   {
      this._container = builder.Build();
   }
   public object GetService( Type serviceType )
   {
      try
      {
         return _container.Resolve( serviceType );
      }
      catch { return null; }
   }

   public IEnumerable GetServices( Type serviceType )
   {
      try
      {
         var enumerableType = typeof( IEnumerable ).MakeGenericType( serviceType );
         return _container.Resolve( enumerableType ) as IEnumerable;
      }
      catch { return null; }
   }
}

Now, it’s easy to register your types and what should resolver use:

protected void Application_Start()
{
   // register type
   var containerBuilder = new ContainerBuilder();
   containerBuilder.RegisterType().As();

   // set resolver
   DependencyResolver.SetResolver(
      new AutoFacDependencyResolver( containerBuilder ) );
}

MongoLab Rest Client

Lascia un commento

I love build ASP.NET MVC projects using C# for this reason I’m searching an inexpensive way for publish my web projects using PaaS approach. After this search I choose AppHarbor solution for host application but for storage I wanted to experiment a Nosql database because I like flexibility of schema feature and there are many free solutions in internet.
I found MongoLab a cloud MongoDB hosting that provide 240MB without costs. The main way for access to mongodb database on mongolab are rest api very simple to use, but I’m .net developer so I created a small library for manage database using only C# classes. I called it MongoLab-Rest-Client and I release it on GitHub (yes I wanted try also git :) ).

What can we do with MongoLab-Rest-Client? Today all crud operations on our entities.

Steps:
1) Sign up to http://mongolab.com
2) Get the apikey ( ex. 123456789012345678901234 )
3) Write code:

var client = new MRestClient( “mydb” );
client.Apikey = “12345678901234567890123″;

// store a new entity
var obj = new Product();
var result = client.Create( obj );

// make a query using criteria api
var criteria = new Criteria();
criteria.Add( Restriction.Or
.Add( Restriction.Eq( “Name”, “name1″ ) )
.Add( Restriction.Eq( “Name”, “name2″ ) ) )
.Add( Restriction.Lte( “Quantity”, 2 ) );
IList products = client.GetByCriteria( criteria );

Only easy C# code and without define a schema on database.

ALTernative Paas a Windows Azure

Lascia un commento

Per chi sviluppa con .Net e vuole provare a fare qualcosa con il cloud sicuramente la prima scelta è Windows Azure, ma io ultimamente mi sento molto ALT.NET e allora ho deciso di cercare qualche altra soluzione PaaS (Platform As A Service) magari a prezzi più bassi, ed ho trovato AppHarbor.

AppHarbor gestisce sia il deployment che la fase di runtime delle applicazioni .net.
E’ possibile fare il push del codice, in pratica, da tutti i vcs e dvcs oggi disponibili (git, mercurial, svn, tfs…), AppHarbor farà la build, lancerà i nostri test e se questi daranno esito positivo farà il deployment sull’application server e noi sviluppatori riceveremo tutte le notifiche.

In fase di esecuzione AppHarbor gestirà la scalabilità dell’applicazione (possiamo acquistare più istanze) e il bilanciamento del carico delle richieste.

Una caratteristiche che mi piace molto è l’estendibilità della piattaforma, in quanto AppHarbor mette a disposizione delle api per consentirci di sviluppare nuovi add-on come ad esempio supportare un nuovo vcs o un nuovo sistema di notifiche.

Una chicca è il catalogo degli add-on (in continua crescita) per “pluggare” servizi nelle nostre applicazioni come dbms (sqlserver,mysql,mongodb,redis) o gestiori di log (airbrake), un vero e proprio store di servizi per le applicazioni.

Per chi vuole cominciare a provarlo i prezzi mi sembrano competitivi e la prima istanza è gratis.

When the model is legacy.

Lascia un commento

I started a new Asp.Net MVC project with an existing domain model and DAL logic. Unfortunately “the legacy domain model” was made for different data access logic (client-server) while I need to show to show information in a different way.
Searching an easy solution to adapt old logic (Building) to new logic (BuildingDTO) presentation I found Aftermap method of Automapper.
Below the code that I wrote:

namespace LegacyDomain
{
 public class Building
 {
   public int Id { get; set; }
   public IList Resources { get; set; }
   //.....
 }

 public class Resource
 {
   public int Id { get; set; }
   public byte[] Bytes { get; set; }
   public ResourceType RType { get; set; }
  }

  public enum ResourceType { SmallPhoto, BigPhoto }
}

namespace DTO
{
 public class BuildingDTO
 {
   public int Id { get; set; }
   public int SmallPhotoId { get; set; }
   public int BigPhotoId { get; set; }
 }
}

Mapper.CreateMap()
      .AfterMap( ( i, d ) => d.SmallPhotoId = i.Resources
         .Where( r => r.RType == ResourceType.SmallPhoto )
         .Select( r => r.Id ).SingleOrDefault() )
      .AfterMap( ( i, d ) => d.BigPhotoId = i.Resources
         .Where( r => r.RType == ResourceType.BigPhoto )
         .Select( r => r.Id ).SingleOrDefault() )

EF 4.1 – OnModelCreating

Lascia un commento

Sebbene EF 4.1 si preoccupa di generare il database per noi, abbiamo ancora la possibilità di gestire come questo debba essere strutturato (nomi delle tabelle, chiavi primarie, tipi delle colonne ecc..).

Per intervenire su questi aspetti ci basterà fare l’override del metodo OnModelCreating del nostro DbContext:

public class ADMDbContext : DbContext
{
        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }

        protected override void OnModelCreating( DbModelBuilder modelBuilder )
        {
            modelBuilder.Entity<User>().ToTable( "Users" );

            modelBuilder.Entity<User>().HasKey( o => o.Id );
            modelBuilder.Entity<User>().Property( o => o.UserName ).IsRequired();

            modelBuilder.Entity<Role>().HasKey( o => o.Id );
            modelBuilder.Entity<Role>().Property( o => o.Name ).IsRequired();

            base.OnModelCreating( modelBuilder );
        }
}

Entity Framework 4.1 – Introduzione alle novità

Lascia un commento

Devo ammetterlo la nuova versione di EF la 4.1 mi sta piacendo molto, certo il team di EF ha ancora molto lavoro da fare per raggiungere il livello di NHibernate, il quale rimane ancora oggi il miglior ORM per chi vuol sviluppare con la piattaforma .NET, ma sono sulla strada giusta.

La versione 4.1 di EF, introduce il nuovo modello di sviluppo code-first, che si affianca alle altre due modalità model-first e database-first, già presenti nella precedente versione.
Personalmente trovo il nuovo approccio code-first più vicino al mio modo di sviluppare codice, in quanto ho delle preferenze per lo sviluppo DDD (Domain Driven Development).

In pratica la prima cosa che faccio quando inizio un nuovo progetto è quello di definire le entità che meglio modellano lo scenario (attraverso la scrittura di classi C#) in cui dovrà operare l’applicazione che dovrò realizzare, senza dovermi preoccupare (inizialmente) di come queste debbano essere persistite. Dal punto di vista del codice.

public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}

L’unico overhead aggiunto da EF 4.1 è la definizione di una classe che estenderà DbContext, la quale rappresenta in punto d’ingresso per gestire la persistenza delle entità. Ad esempio:

public class MyContext : DbContext
{
public DbSet<User> Users { get; set; }
}

Finito!

Nessun database creato, nessuna tabella definita.

Adesso ci basterà scrivere una normale query Linq per recupare i dati dal database:

var ctx = new MyContext();

var query = from o in ctx.Users select o;

var users = query.ToList();

Cosa è successo?

Semplicemente (si fa per dire), al momento dell’esecuzione del metodo ToList() il motore di EntityFramework genererà per noi un database (sql server) con il nome MyContext e le tabelle necessarie a persistere le classi definite come DbSet nella classe MyContext, infone verrà effettuata la query T-Sql generata dal provider Linq dell’Entity Framework.

NHDay Introduction to LINQ2NH

Lascia un commento

it.comp.dotnet

Lascia un commento

Finalmente è stato attivato it.comp.dotnet, la newsgroup italiana dedicata a .net.

Il manifesto del gruppo:

+——————————————————–

it.comp.dotnet
Infrastruttura, linguaggi, framework e strumenti relativi alle
implementazioni della Common Language Infrastructure

+——————————————————–

Il gruppo it.comp.dotnet e` dedicato alle discussioni attinenti lo standard
ISO/IEC 23271 in tutte le sue implementazioni, le tecnologie ad esso
correlate e lo sviluppo di applicazioni basate su tale standard.

Sono, quindi, incluse le discussioni riguardanti i seguenti argomenti:
+ varie implementazioni dello standard (framework .NET, MONO…);
+ compilatori;
+ linguaggi (C#, VB.NET…);
+ ambienti di sviluppo (Visual Studio, MonoDevelop…);
+ piattaforme di sviluppo, librerie di classi, tecnologie varie inerenti
(WPF, WCF, ASP.NET, AJAX, ADO.NET, Castle, NUnit, Rhino, NHibernate …)
+ strumenti e tecnologie accessorie allo sviluppo (MSBuild, CCNet, Nant,
…)
Sono anche da considerarsi comprese le discussioni riguardanti la
migrazione verso .NET da altre tecnologie e viceversa.

MVC

Lascia un commento

Voci più vecchie

Follow

Get every new post delivered to your Inbox.

Join 70 other followers