F# Code-First Development with Entity Framework 4.1

F# Code-First Development with Entity Framework 4.1

Rate This
  • Comments 16

By Jack Hu

As the word “code-first” implies, the EF 4.1 offers a code centric data programming paradigm. From a coder’s point of view, it requires little effort to map a very clean object model to a database. This style of programming is idea for explorative, bottom-up kind fsharp programmers. Since EF 4 CTP4 release, there have already been many buzzes. The following two blogs have in-depth EF 4.1 feature overview.

In this blog, I demonstrate how to use EF 4.1 Code-first in Fsharp 2.0 to save a record into a SQL CE. I also provide workarounds for several practical issues may block fsharp programmers.

Step0: Install Software Packages

Step1: Create a New F# Application

image001

Add Project references: Unlike C#, Fsharp compiler requires additional references from System.Data and System.Data.Entity to resolve base types inherited by EF 4.1

image002

The EntityFramework.dll is under $\Program Files (x86)\Microsoft ADO.NET Entity Framework Feature CTP5\Binaries\EntityFramework.dll

Step2: Create a Model

In this example, I create a CLCars class. The class contains a single DbSet of Cars. In Car class I have a field of ID (serve as the primary key) and a field of Name.

image003

In the driver code, I create a new CLCars database, added a Car to it and flush out to the database.

image004

Step3: Pointing to a Database

I love SQL CE 4.0, especially because user no longer needs to generate a primary key while adding a record. Yeah! In this example, I add an app.config file and embed the database connection string. I also make sure the connectionString Name property is the same as my DbContext class name, so that the EF 4.1 automatically generates a database at runtime.

image005

Step4: Run and Verify data

After build and run app, I use SQL Server Compact 4.0 Tooling for VS2010 to verify the database, the table and the data are added correctly.

image006

During the ad-hocking, I also encountered several issues. Here is how I work around them.

Issue#1: EF 4.1 does not support nested type; the model can NOT be used inside a Module or a Script

Trying to put the model inside a module, I got a run time exception: “The type 'Program+Car' is not a supported entity type.”

image007

Digging into fsharp assembly using reflector, we can see the Fsharp script and module generate a nested-type which is not supported in EF 4.1

image008

The work around is to put the model code inside a namespace DataModel

The VB module shares the same limitation. The work around in below example is to move the Car and CLCars class outside the Module1.

image009

Issue#2: Property initialization on DBContext class need to use [<DefaultValue>] attribute with Explicit Fields

During EF DbContext construction, it will reflect on all its properties and initialized them with database mapping values. After base construction, if the inhered Fsharp class calls its constructor with property initialization, it will override the property value that base class already initialized.

In the following example, the DbContext constructor will initialize m_cars to a DbSet<Car> mapping value, but the inhered CLCars constructor will reinitialize n_cars to NULL. This could cause a NullReferenceException at runtime.

image010

image011

EF 4.1 code-first is a great tool for F# 2.0 data programming. As Fsharp 3.0 features become clearer in the next few months, I am supper exited and feel good about them. I expect Fsharp 3.0 will take these experiences to the next level. Happy coding! 

Code example is published @ http://code.msdn.microsoft.com/F-Code-First-Development-326dede1

Leave a Comment
  • Please add 5 and 3 and type the answer here:
  • Post
  • good! As a big fan of F# this is pretty much needed. Thanks, Mark

  • @Mark, I am glad to hear that.

  • Why spend time on F#?? I don't see any point in this language at all.

  • @Shimmy

    This video channel9.msdn.com/.../C9-Lectures-Dr-Don-Syme-Introduction-to-F-1-of-3 & the page  www.tryfsharp.org/FunctionalProg.aspx

    explains F# value propositions. I like F# is because of the following advantages:

    SIMPLICITY: unlike OO programming language, having to keep track of Class object changes. It makes functional data structures simpler to use, especially in the context of concurrency.

    .NET PLATFORM: Fsharp is a part of .net, you can consume or be consumed just like C# and VB.net

  • @Shimmy - Don't worry about it. Just go back to programming in Blub.

    www.paulgraham.com/avg.html

  • I didn't mind your screen shots until Mr Hanselman pointed them out...

    www.hanselman.com/.../TakingProperScreenshotsInWindowsForBlogsOrTutorials.aspx

  • great screen shot tip, thank you!

  • I recently read an article (ecs.victoria.ac.nz/.../plateau10-markstrum.pdf) (could I say study) about how Programming Language claims over the last say 50 years have been largely backed by proof or evidence. Paul Graham's article is tantamount to that.

    I believe the functional language paradigm claims nonetheless... F# is a fantastic language.

  • *meant largely unsubstantiated/unsupported

  • @ David Grenier, Thank you!

  • Thanks!

    It seems like the right way of insert/update/delete is:

    db.Entry(c).State <- EntityState.Added //add when savechanges

    db.Entry(c).State <- EntityState.Modified //update when savechanges

    db.Entry(c).State <- EntityState.Deleted //delete

    and c (=car) is identified by primary key.

  • Thanks!

    It seems like the right way to insert/update/delete is:

    db.Entry(c).State <- EntityState.Added //add when savechanges

    db.Entry(c).State <- EntityState.Modified //update when savechanges

    db.Entry(c).State <- EntityState.Deleted //delete

    and c (=car) is identified by primary key.

  • Jack, I've posted a refreshed version (EF5.0 Beta + Dev11 Beta) at social.msdn.microsoft.com/.../3139c667-bdfb-482a-8f3b-b754deeae9af

  • Hmmm the link to the code just show a message saying there is not posted any files ???

  • I've recently tried if it's doable with F# record types annotated with [<CLIMutable>], interesting experiment that brought some positive results:

    [url]bprzygoda.github.com/.../FSharp-and-EntityFramework-Code-First.html[/url]

Page 1 of 2 (16 items) 12