Sep 1, 2010

Entity Framework Feature CTP4

EFF CTP4 is a technical preview built on EF4 that was released on .Net framework 4.0.  It’s main purpose is to simplify usage in code first scenarios, so I wanted to go over a simple case here.

-==- Requirements & Preparation –==-
  1. If you don’t already have .Net framework 4.0, install that
  2. Download and install EFF CTP4
  3. Create a new console (or whatever you want to use for testing) project
  4. Add reference to Microsoft.Data.Entity.Ctp and System.Data.Entity
-==- POCOs & DBContext –==-

Creating the mapping and context is pretty easy:
public class Person {
    public long Id { get; set; }
    public string Name { get; set; }
    public virtual IList<Address> Addresses { get; set; }
}

public class Address {
    public long Id { get; set; }
    public string Street { get; set; }
    public string ZipCode { get; set; }
}

public class PersonCatalog : DbContext
{
    public PersonCatalog(string connectionString) : base(connectionString) { }

    public DbSet<person> Persons { get; set; }
    public DbSet<address> Addresses { get; set; }
}


After using the DBContext for the first time, it’ll create the database based on the context and POCOs used in it.

using (var dc = new PersonCatalog("PersonDB")) 
{
    dc.Persons.Add(new Person { Name = "James" });
    dc.SaveChanges(); 
}





As you can see, it automatically deduced primary and foreign keys by convention. You can also effect the creation (or prevent it) by setting the following:


Database.SetInitializer<PersonCatalog>(new CreateDatabaseOnlyIfNotExists<PersonCatalog>());

Other options are:
  • RecreateDatabaseIfModelChanges
  • AlwaysRecreateDatabase

 -==- Mapping – automatic & attributes –==-

If convention based mapping is not enough, you can specify more detailed metadata either by adding attributes to your POCO classes or using custom mapping inside the data context initialization.

For example:

public class Person {
    [Key]
    public string SocialSecurityNumber { get; set; }
    ...
}

Other supported annotations are

  • Key
  • StringLength
  • ConcurrencyCheck
  • Required
  • Timestamp
  • DataMember
  • RelatedTo
  • MaxLength
  • StoreGenerated

More information on these can be found on EF Design blog.

-==- Mapping – custom mapping with fluent API –==-

You can add to your existing metadata by overriding the OnModelCreating method in DBContext and using the ModelBuilders fluent configuration.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity().HasKey(p => p.Id);
    modelBuilder.Entity().Property(p => p.Name).Optional = false;
}

-==- More resources –==-

This was a very short intro to EFFCTP4, so take a look around for more info on it.

Release notes for EFF CTP4 on Ado.Net blog
More tips & tricks by Ro Miller

0 comments:

Post a Comment