Logentries.com and F#

I recently was working on a project that has a fair bit of legacy code.  One of the pieces of the project is an logging service whose interface is this:

1 public interface ILoggingRepository 2 { 3 void LogMessage(String message); 4 void LogException(String message, Exception exception); 5 }


There are 2 or 3 different implementations of the logging repository – one that covers the windows logs, one that writes to azure service bus, one that writes to nothing (and in-memory one used for testing).  I thought about using Logentries as place to write the messages to.  I created an account and set up my first log

image image

Note that the log also gets a token (a guid) that I will use to send messages to the log at the bottom of the page.

I then fired up visual studio and created a new FSharp project and added a reference from the CSharp project to the FSharp project.  I then added an associated unit test class to the existing unit test project:


I then went back to Logentries and read the api documentation about posting to the log here.   They suggested either log4net or NLog.  For no particular reason, I picked NLog.  I fired up Nuget and installed the Logentries.NLog package


I then read further down the documentation and yuck, there is tons of places where you have to add to the configuration file.  I am trying to maintain a clean separation of concerns in the app and this intertwines the working code with the .config file.  Also, the other implementations don’t use the .config so I would like to keep consistant there.  After bouncing around in the api for a bit, I went to stack overflow and asked if there was a way I could implement without the .config file.  Sure enough, the dev team was kind enough to answer.  I went ahead and implemented their code (after porting it from C#)  in my project like so:

1 namespace ChickenSoftware.LoggingExample.FS 2 3 open NLog 4 open System 5 open NLog.Targets 6 open NLog.Config; 7 open ChickenSoftware.LoggingExample 8 9 type LogEntriesLoggingRepository(logEntriesToken:string) = 10 let target = new LogentriesTarget() 11 let config = new LoggingConfiguration() 12 do target.Token <- logEntriesToken 13 do target.Ssl <- true 14 do target.Debug <- true 15 do target.Name <- "Logentries" 16 let layout = Layouts.Layout.FromString("${date:format=ddd MMM dd} ${time:format=HH:mm:ss} ${date:format=zzz yyyy} ${logger} : ${LEVEL}, ${message}") 17 do target.Layout <- layout 18 do target.HttpPut <- false 19 do config.AddTarget("Logentries2",target) 20 let loggingRule = new LoggingRule("*", LogLevel.Debug, target) 21 do LogManager.Configuration.AddTarget("targetName", target) 22 do LogManager.Configuration.LoggingRules.Add(loggingRule) 23 do LogManager.Configuration.Reload() |> ignore 24 let logger = LogManager.GetCurrentClassLogger() 25 26 interface ILoggingRepository with 27 member this.LogMessage(message) = 28 logger.Log(LogLevel.Warn, message) 29 member this.LogException(message, exn) = 30 logger.LogException(LogLevel.Error,message,exn)

I then went into the unit test and attempted to generate a log message:

1 public class LogEntriesLoggingRepositoryTests 2 { 3 ILoggingRepository _repository = null; 4 public LogEntriesLoggingRepositoryTests() 5 { 6 string logEntriesToken = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; 7 _repository = new LogEntriesLoggingRepository(logEntriesToken); 8 } 9 10 [TestMethod] 11 public void LogMessage_ReturnsExpected() 12 { 13 _repository.LogMessage("This is a test"); 14 15 } 16 }

Unfortunately, when I ran it, I got the following exception, even though I marked the .dlls to be copied

image image

So back to Nuget, where I added in the Logentries.NLog to the Tests project.  I feel really dirty by doing it:


I then ran the test again but I got this exception:


When I added a break to the code and stepped through, I found it was on the LogManager.Configuration.


Apparently, the only way out of this pickle is to add some basic entries to the .config file <sigh>:

1 <?xml version="1.0" encoding="utf-8"?> 2 <configuration> 3 <configSections> 4 <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" /> 5 </configSections> 6 <runtime> 7 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> 8 <dependentAssembly> 9 <assemblyIdentity name="NLog" publicKeyToken="5120e14c03d0593c" culture="neutral" /> 10 <bindingRedirect oldVersion="" newVersion="" /> 11 </dependentAssembly> 12 </assemblyBinding> 13 </runtime> 14 <nlog> 15 <extensions> 16 <add assembly="LogentriesNLog" /> 17 </extensions> 18 <targets> 19 <target name="logentries" type="Logentries" debug="true" httpPut="false" ssl="false" layout="${date:format=ddd MMM dd} ${time:format=HH:mm:ss} ${date:format=zzz yyyy} ${logger} : ${LEVEL}, ${message}" /> 20 </targets> 21 <rules> 22 <logger name="*" minLevel="Debug" appendTo="logentries" /> 23 </rules> 24 </nlog> 25 </configuration>

After I added it, the test ran green.


Alas, nothing was showing up in the log!


After some back and forth with the Logentries team, it became clear that the thread was terminating before the Logentries library had a chance to post it to the service.  This was proven by adding a Thread.Sleep to the test:

1 public void LogMessage_ReturnsExpected() 2 { 3 _repository.LogMessage("This is a test"); 4 Thread.Sleep(500); 5 6 }


So what to do?  The api does not have an async implementation so I can’t await it and if I leave that Thread.Sleep as is, the main thread will be blocked.  I decided to add an async implementation to the interface

1 public interface ILoggingRepository 2 { 3 void LogMessage(String message); 4 Task LogMessageAsync(String message); 5 void LogException(String message, Exception exception); 6 Task LogExceptionAsync(String message, Exception exception); 7 }

I then updated the repository like so:

1 interface ILoggingRepository with 2 member this.LogMessage(message) = 3 logger.Log(LogLevel.Warn, message) 4 member this.LogMessageAsync(message) = 5 Tasks.Task.Run(fun _ -> logger.Log(LogLevel.Warn, message) 6 Thread.Sleep(500)) 7 member this.LogException(message, exn) = 8 logger.LogException(LogLevel.Error,message,exn) 9 member this.LogExceptionAsync(message, exn) = 10 Tasks.Task.Run(fun _ -> logger.LogException(LogLevel.Error,message,exn) 11 Thread.Sleep(500))

And then I added an async unit test like so:

1 [TestMethod] 2 public void LogMessageAsync_ReturnsExpected() 3 { 4 var task = _repository.LogMessageAsync("This is an async test"); 5 task.Wait(); 6 }

And sure enough, green (note that the async test takes longer than 500MS) and the expected side-effect:



So now another CSharp shop has some FSharp sprinkled into their code base.  Note the code actually used is slightly different b/c  the code as written will keep adding more and more targets, which is not what we want.

F# Record Types with SqlProvider Code-Last

As I talked about last week, I was looking at different ways of using the Entity Framework type provider to map to my domain model.  While I was working on the process,  Ross McKinley saw some of my whining on Twitter and suggested that I take a look at SqlProvider.


He made a good case to use this type provider over entity framework.  Specifically:

  • There is no code bloat/file bloat/code-gen issues that you get with EF
  • It targets Sql Server like EF, but also can handle Oracle, Postgres, MySql, and other RDBMS
  • It has had a update in the last year

So that was a good enough reason to take a look.  The project site is a bit lacking in terms of examples but between what is on GitHub and on Ross’s blog, you can get a pretty good idea of how to accomplish basic crud tasks.  I was interested in how well it handles nested types and F# choice types.  I fired up Visual Studio and installed it from nuget.

I then created the same domain types I was working with earlier –> note the Choice type for gender.

1 #r "../packages/SQLProvider.0.0.9-alpha/lib/net40/FSharp.Data.SqlProvider.dll" 2 3 open System.Linq 4 open FSharp.Data.Sql 5 open System.Security.Principal 6 7 type sqlSchema = SqlDataProvider< 8 ConnectionString = @"Server=.;Database=FamilyDomain;Trusted_Connection=True;", 9 UseOptionTypes = true > 10 11 let context = sqlSchema.GetDataContext() 12 13 //Local Idomatic Types 14 type Gender = Male | Female 15 [<CLIMutable>] 16 type Pet = {Id:int; ChildId:int; GivenName:string} 17 [<CLIMutable>] 18 type Child = {Id:int; FirstName:string; Gender:Gender; Grade:int; Pets: Pet list} 19 [<CLIMutable>] 20 type Address = {Id:int; State:string; County:string; City:string} 21 [<CLIMutable>] 22 type Parent = {Id:int; FirstName:string} 23 [<CLIMutable>] 24 type Family = {Id:int; LastName:string; Parents:Parent list; Children: Child list; Address:Address} 25 26

I then added in the same code that I used for the Entity Framework Type Provider, made some changes (like you get subtypes via querying the foreign key and I am not using Linq to query the data store

1 let MapPet(efPet: entity.dataContext.``[dbo].[Pet]Entity``) = 2 {Id=efPet.Id; ChildId=efPet.ChildId; GivenName=efPet.GivenName} 3 4 let MapGender(efGender) = 5 match efGender with 6 | "Male" -> Male 7 | _ -> Female 8 9 let MapChild(efChild: entity.dataContext.``[dbo].[Child]Entity``) = 10 let pets = efChild.fk_Pet_Child |> Seq.map(fun p -> MapPet(p)) 11 |> Seq.toList 12 {Id=efChild.Id; FirstName=efChild.FirstName; 13 Gender=MapGender(efChild.Gender); 14 Grade=efChild.Grade;Pets=pets} 15 16 let GetPet(id: int)= 17 context.``[dbo].[Pet]`` 18 |> Seq.where(fun p -> p.Id = id) 19 |> Seq.head 20 |> MapPet 21 22 let GetChild(id: int)= 23 context.``[dbo].[Child]`` 24 |> Seq.where(fun c -> c.Id = id) 25 |> Seq.head 26 |> MapChild 27 28 let myPet = GetPet(1) 29 30 let myChild = GetChild(1)


And then I added some code to insert a new pet

1 let SavePet(pet: Pet)= 2 let ssPet = context.``[dbo].[Pet]``.Create() 3 ssPet.ChildId <- pet.ChildId 4 ssPet.GivenName <- pet.GivenName 5 context.SubmitUpdates() 6 7 let newPet = {Id=0;ChildId=1;GivenName="Kiss"} 8 SavePet(newPet) 9 10 let failurePet = {Id=0;ChildId=0;GivenName="Should Fail"} 11 SavePet(failurePet)

And pow on the expected happy path


and pow pow on the expected exception

System.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "fk_Pet_Child". The conflict occurred in database "FamilyDomain", table "dbo.Child", column ‘Id’.

The statement has been terminated.

   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

So this is pretty cool.  But then it got better, I showed some of this code to Ross and he told me I was doing everything wrong.  Basically, I need to think about the get code less imperative linq and more like computed expressions.  The biggest downside to how I wrote the gets is that the TP would pull all of the records from the database locally before filtering them.  So going back to the documentation, I changed the getPet functional to this

1 let GetPet(id: int)= 2 query {for p in context.``[dbo].[Pet]`` do 3 where (p.Id = id) 4 select {Id=p.Id; ChildId=p.ChildId; GivenName=p.GivenName}} 5 |> Seq.head 6

And it still works


The nice thing is that I no longer need the mapPet function as the project happens in the select clause.  So this is pretty cool and very powerful.  Time to learn some more query syntax!

F# Record Types with Entity Framework Code-Last

So based on the experience with code-first, I decided to look at using EF code-last (OK, database first).   I considered three different possibilities

  1. 1) Use AutoMapper
  2. 2) Use Reflection
  3. 3) Hand-Roll everything


If you are not familiar, Automapper is a library to allow you to,well, map types. The first thing I did was to create a database schema like this:

1 use FamilyDomain 2 3 CREATE TABLE Family 4 ( 5 Id int NOT NULL IDENTITY(1,1) PRIMARY KEY, 6 LastName varchar(255) NOT NULL 7 ) 8 9 CREATE TABLE Parent 10 ( 11 Id int NOT NULL IDENTITY(1,1) PRIMARY KEY, 12 FamilyId int NOT NULL, 13 FirstName varchar(255) NOT NULL 14 ) 15 16 CREATE TABLE Child 17 ( 18 Id int NOT NULL IDENTITY(1,1) PRIMARY KEY, 19 FamilyId int NOT NULL, 20 FirstName varchar(255) NOT NULL, 21 Gender varchar(10) NOT NULL, 22 Grade int NOT NULL 23 ) 24 25 CREATE TABLE Pet 26 ( 27 Id int NOT NULL IDENTITY(1,1) PRIMARY KEY, 28 ChildId int NOT NULL, 29 GivenName varchar(255) NOT NULL 30 ) 31 32 CREATE TABLE HomeAddress 33 ( 34 Id int NOT NULL IDENTITY(1,1) PRIMARY KEY, 35 FamilyId int NOT NULL, 36 StateCode varchar(2) NOT NULL, 37 County varchar(255) NOT NULL, 38 City varchar(255) NOT NULL 39 ) 40 41 ALTER TABLE Parent 42 ADD CONSTRAINT fk_Parent_Family 43 FOREIGN KEY (FamilyId) 44 REFERENCES Family(Id) 45 46 ALTER TABLE HomeAddress 47 ADD CONSTRAINT fk_HomeAddress_Family 48 FOREIGN KEY (FamilyId) 49 REFERENCES Family(Id) 50 51 ALTER TABLE Child 52 ADD CONSTRAINT fk_Child_Family 53 FOREIGN KEY (FamilyId) 54 REFERENCES Family(Id) 55 56 ALTER TABLE Pet 57 ADD CONSTRAINT fk_Pet_Child 58 FOREIGN KEY (ChildId) 59 REFERENCES Child(Id) 60 61 62 INSERT Family VALUES 63 ('Andersen') 64 65 INSERT Parent VALUES 66 (1,'Thomas'), 67 (1,'Mary Kay') 68 69 INSERT Child VALUES 70 (1,'Henriette Thaulow','Female',5) 71 72 INSERT Pet VALUES 73 (1,'Fluffy') 74 75 INSERT HomeAddress VALUES 76 (1,'WA','King','Seattle') 77

I then  installed automapper and entity framework type provider to a FSharp project.

1 #r @"../packages/AutoMapper.3.3.0/lib/net40/AutoMapper.dll" 2 #r "FSharp.Data.TypeProviders.dll" 3 #r "System.Data.Entity.dll" 4 5 open Microsoft.FSharp.Data.TypeProviders 6 open System.Data.Entity 7 open AutoMapper 8 9 //Entity Framework Types via Type Provider 10 let connectionString = @"Server=.;Initial Catalog=FamilyDomain;Integrated Security=SSPI;MultipleActiveResultSets=true" 11 type EntityConnection = SqlEntityConnection<ConnectionString="Server=.;Initial Catalog=FamilyDomain;Integrated Security=SSPI;MultipleActiveResultSets=true",Pluralize=true> 12

I then created some local FSharp record types the reflect the domain:

1 type Pet = {Id:int; GivenName:string} 2 type Child = {Id:int; FirstName:string; Gender:string; Grade:int; Pets: Pet list} 3 type Address = {Id:int; State:string; County:string; City:string} 4 type Parent = {Id:int; FirstName:string} 5 type Family = {Id:int; Parents:Parent list; Children: Child list; Address:Address}

So then I was ready to start mapping.  I started with a basic GET to a single type:

1 //AutoMapper setup 2 Mapper.CreateMap<EntityConnection.ServiceTypes.HomeAddress, Address>() 3 4 //Get one from the database 5 let context = EntityConnection.GetDataContext() 6 let addressQuery = query {for address in context.HomeAddresses do select address} 7 let address = Seq.head addressQuery 8 9 //map database to record type 10 let address' = Mapper.Map<Address>(address) 11

And I got a fail:

Source value:

SqlEntityConnection1.HomeAddress —> System.ArgumentException: Type needs to have a constructor with 0 args or only optional args

Parameter name: type

So I added [<CLIMutable>] to the record types like so

1 [<CLIMutable>] 2 type Pet = {Id:int; GivenName:string} 3 [<CLIMutable>] 4 type Child = {Id:int; FirstName:string; Gender:string; Grade:int; Pets: Pet list} 5 [<CLIMutable>] 6 type Address = {Id:int; State:string; County:string; City:string} 7 [<CLIMutable>] 8 type Parent = {Id:int; FirstName:string} 9 [<CLIMutable>] 10 type Family = {Id:int; Parents:Parent list; Children: Child list; Address:Address} 11

And I get the expected results


With one thing kinda interesting.  The State is null because it is defined as “StateCode” on the server and “State” in the domain.  Autopmapper is customizable to allow field name differences so that was a small issue.  Feeling confident, I went ahead and created maps to all of the domain types and pulled down a complex type from the database

1 //AutoMapper setup 2 Mapper.CreateMap<EntityConnection.ServiceTypes.Pet, Pet>() 3 Mapper.CreateMap<EntityConnection.ServiceTypes.Child, Child>() 4 Mapper.CreateMap<EntityConnection.ServiceTypes.HomeAddress, Address>() 5 Mapper.CreateMap<EntityConnection.ServiceTypes.Parent, Parent>() 6 Mapper.CreateMap<EntityConnection.ServiceTypes.Family, Family>() 7 8 //Get Family from the database 9 let context = EntityConnection.GetDataContext() 10 let familyQuery = query {for family in context.Families do select family} 11 let family = Seq.head familyQuery 12 13 //map database to record type 14 let family' = Mapper.Map<Family>(family)

When I attempted to map it, I got a pretty ugly exception

Source value:


   at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)

So the problem is that automapper is not picking up on the foreign keys, which means I have to write the associations by hand.  Ugh!  I then tried to auto map to F# choice types like this:

1 type Gender = Male | Female

No dice.


I quickly spun up another project that uses System.Reflection to map the types.

1 #r "System.Data.Entity.dll" 2 #r "FSharp.Data.TypeProviders.dll" 3 4 open System.Reflection 5 open System.Data.Entity 6 open Microsoft.FSharp.Data.TypeProviders 7 8 let connectionString = "Server=.;Database=FamilyDomain;Trusted_Connection=True;" 9 10 type entityConnection = SqlEntityConnection<ConnectionString = "Server=.;Database=FamilyDomain;Trusted_Connection=True;"> 11 12 let context = entityConnection.GetDataContext() 13 14 //Local Idomatic Types 15 [<CLIMutable>] 16 type Pet = {Id:int; ChildId:int; GivenName:string} 17 [<CLIMutable>] 18 type Child = {Id:int; FirstName:string; Gender:string; Grade:int; Pets: Pet list} 19 [<CLIMutable>] 20 type Address = {Id:int; State:string; County:string; City:string} 21 [<CLIMutable>] 22 type Parent = {Id:int; FirstName:string} 23 [<CLIMutable>] 24 type Family = {Id:int; LastName:string; Parents:Parent list; Children: Child list; Address:Address} 25 26 //Reflection 27 let AssignMatchingPropertyValues sourceObject targetObject = 28 let sourceType = sourceObject.GetType() 29 let targetType = targetObject.GetType() 30 let sourcePropertyInfos = sourceType.GetProperties(BindingFlags.Public ||| BindingFlags.Instance) 31 sourcePropertyInfos 32 |> Seq.map(fun spi -> spi, targetObject.GetType().GetProperty(spi.Name)) 33 |> Seq.iter(fun (spi,tpi) -> tpi.SetValue(targetObject, spi.GetValue(sourceObject,null),null)) 34 targetObject 35 36 37 let newEfPet = entityConnection.ServiceTypes.Pet() 38 let newPet = {Id=0;ChildId=1;GivenName="Duke"} 39 40 AssignMatchingPropertyValues newPet newEfPet 41 42 context.DataContext.AddObject("Pet",newEfPet) 43 context.DataContext.SaveChanges()

Sure enough, reflection does what it is supposed to do:


The problem quickly becomes that by using reflection, I have to hand roll all of the relations.  I might as well use Automapper (though apparently reflection is much faster than Automapper, even on a per-call basis).

Another problem with using reflection is that the field names in the database need to match the domain naming exactly.  Finally, like automapper, there is not out of the box way to map choice types

Hand Roll

On my last stop of the entity framework code-last hit parade, I looked at what it would take to roll my own mappings.  This has the greatest amount of yak shaving because I would have to spin up mapping from the domain and to the domain.  The nice thing is that with that kind of detail, naming mismatches can be handled and the nested hierarchy and choice types are accounted for.  I first started with a basic script that handled the gettting and setting as well as nested types:

1 #r "System.Data.Entity.dll" 2 #r "FSharp.Data.TypeProviders.dll" 3 4 open System.Linq 5 open System.Data.Entity 6 open Microsoft.FSharp.Data.TypeProviders 7 8 let connectionString = "Server=.;Database=FamilyDomain;Trusted_Connection=True;" 9 type entity = SqlEntityConnection<ConnectionString = "Server=.;Database=FamilyDomain;Trusted_Connection=True;"> 10 let context = entity.GetDataContext() 11 12 type Pet = {Id:int; ChildId: int; GivenName:string} 13 type Child = {Id:int; FirstName:string; Gender:string; Grade:int; Pets: Pet list} 14 type Address = {Id:int; State:string; County:string; City:string} 15 type Parent = {Id:int; FirstName:string} 16 type Family = {Id:int; LastName:string; Parents:Parent list; Children: Child list; Address:Address} 17 18 let MapPet(efPet: entity.ServiceTypes.Pet) = 19 {Id=efPet.Id; ChildId=efPet.ChildId; GivenName=efPet.GivenName} 20 21 let MapChild(efChild: entity.ServiceTypes.Child) = 22 let pets = efChild.Pet |> Seq.map(fun p -> MapPet(p)) 23 |> Seq.toList 24 {Id=efChild.Id; FirstName=efChild.FirstName; 25 Gender=efChild.Gender;Grade=efChild.Grade;Pets=pets} 26 27 let GetPet(id: int)= 28 let efPet = context.Pet.FirstOrDefault(fun p -> p.Id = id) 29 MapPet(efPet) 30 31 let GetChild(id: int)= 32 let efChild = context.Child.FirstOrDefault(fun c -> c.Id = id) 33 MapChild(efChild) 34 35 let myPet = GetPet(1) 36 37 let myChild = GetChild(1) 38

Of all of the implementations, the hand-rolled actually made the most sense to me.  it was clean and, most importantly, it worked.


I then swapped out a Choice type for gender (was a string)

1 type Gender = Male | Female 2 type Pet = {Id:int; ChildId: int; GivenName:string} 3 type Child = {Id:int; FirstName:string; Gender:Gender; Grade:int; Pets: Pet list} 4 type Address = {Id:int; State:string; County:string; City:string} 5 type Parent = {Id:int; FirstName:string} 6 type Family = {Id:int; LastName:string; Parents:Parent list; Children: Child list; Address:Address} 7

And then added the choice type mapping and then updated child mapping

1 let MapGender(efGender) = 2 match efGender with 3 | "Male" -> Male 4 | _ -> Female 5 6 let MapChild(efChild: entity.ServiceTypes.Child) = 7 let pets = efChild.Pet |> Seq.map(fun p -> MapPet(p)) 8 |> Seq.toList 9 {Id=efChild.Id; FirstName=efChild.FirstName; 10 Gender=MapGender(efChild.Gender); 11 Grade=efChild.Grade;Pets=pets} 12

Sure enough, it worked like a champ


And finally, I tested the add on both the happy path and an expected exception.

1 let SavePet(pet: Pet)= 2 let efPet = entity.ServiceTypes.Pet() 3 efPet.ChildId <- pet.ChildId 4 efPet.GivenName <- pet.GivenName 5 context.DataContext.AddObject("Pet",efPet) 6 context.DataContext.SaveChanges() 7 8 let newPet = {Id=0;ChildId=1;GivenName="Lucky Sue"} 9 SavePet(newPet) 10 11 let failurePet = {Id=0;ChildId=0;GivenName="Should Fail"} 12 SavePet(failurePet)

  Both worked as expected.  Here is the exception case where there is not a child to be associated to a pet:

System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. —> System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "fk_Pet_Child". The conflict occurred in database "FamilyDomain", table "dbo.Child", column ‘Id’.

The statement has been terminated.

   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

So of all three ways, hand-rolling worked the best for me.

F# Record Types With Entity Framework Code-First

I was spinning up a data layer in a new FSharp project and I thought I would take EF Code-first out for a test drive.  I have use EF-CF in a couple of C# projects so I am familiar with the premise (and the promise) of code-first.  The FSharp project uses record types, nested record types, and choice types exclusively so I I thought of attaching each of these types for code first in turn.  The first article that I ran across was this one, which seemed like a good start.  I went ahead a created a family record type like so, matching the example verbatim except I swapped out the class implementation with a record type:


1 #r "../packages/EntityFramework.6.1.2/lib/net45/EntityFramework.dll" 2 3 open System.Collections.Generic 4 open System.ComponentModel.DataAnnotations 5 open System.Data.Entity 6 7 type Family = {Id:int; LastName:string; IsRegistered:bool} 8 9 type CLFamily() = 10 inherit DbContext() 11 [<DefaultValue>] 12 val mutable m_families: DbSet<Family> 13 member public this.Families with get() = this.m_families 14 and set v = this.m_families <- v 15 16 let db = new CLFamily() 17 let family = {Id=0;LastName="New Family"; IsRegistered=true} 18 db.Families.Add(family) |> ignore 19 db.SaveChanges() |> ignore 20

But I ran into this:



So I added the Key attribute to the Record type


So I hit up stack overflow with this question and sure enough, I forgot to add a reference to that assembly.  Once I added it, then it compiled.  I then ran the script and I got the following error message:

1 <add name="CLFamily" 2 connectionString="Server=.;Database=FamilyDomain;Trusted_Connection=True;" 3 providerName="System.Data.SqlClient"/> 4



Ugh!  It was still hitting the default connection string.    I went ahead and adjusted my script to account for the connection string and I swapped out the backing values with CLIMutable:

1 #r "../packages/EntityFramework.6.1.2/lib/net45/EntityFramework.dll" 2 #r "C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETFramework/v4.5.1/System.ComponentModel.DataAnnotations.dll" 3 4 open System.Collections.Generic 5 open System.ComponentModel.DataAnnotations 6 open System.Data.Entity 7 8 [<CLIMutable>] 9 type Family = {[<Key>]Id:int; LastName:string; IsRegistered:bool;} 10 11 12 type FamilyContext() = 13 inherit DbContext() 14 [<DefaultValue>] val mutable families: DbSet<Family> 15 member this.Families with get() = this.families and set f = this.families <- f 16 17 let context = new FamilyContext() 18 let connectionString = "Server=.;Database=FamilyDomain;Trusted_Connection=True;" 19 context.Database.Connection.ConnectionString <- connectionString 20 let family = {Id=0; LastName="Test"; IsRegistered=true} 21 context.Families.Add(family) |> ignore 22 context.SaveChanges() |> ignore

And sure enough, the table is created in the database and the record is persisted:

image image

And the cool thing is that even though this is a record type, the Id does adjust to the identity value given by the database.

With that out of the way, I went to tackle nested types.  I added a Child class and a list of children to the family class. 

1 [<CLIMutable>] 2 type Child = {[<Key>]Id:int; FamilyId: int; FirstName:string; Gender:string; Grade:int} 3 4 [<CLIMutable>] 5 type Family = {[<Key>]Id:int; LastName:string; IsRegistered:bool; Children:Child list} 6 7 type FamilyContext() = 8 inherit DbContext() 9 [<DefaultValue>] val mutable families: DbSet<Family> 10 member this.Families with get() = this.families and set f = this.families <- f 11 [<DefaultValue>] val mutable children: DbSet<Child> 12 member this.Chidlren with get() = this.children and set c = this.children <- c 13 14 let context = new FamilyContext() 15 let connectionString = "Server=.;Database=FamilyDomain;Trusted_Connection=True;" 16 context.Database.Connection.ConnectionString <- connectionString 17 let children = [{Id=0; FamilyId=0; FirstName="Test"; Gender="Male"; Grade=5}] 18 let family = {Id=0; LastName="Test"; IsRegistered=true; Children=children } 19 context.Families.Add(family) |> ignore 20 context.SaveChanges() |> ignore

Everything compiled and  ran, but the Children table was not added to the database –> though the new record was added.

image image image

Going back to stack overflow, it looks like EF Code First will not auto-update the schema unless you add some more glue code.  Ugh.  At that point, I might as well give up on code-first if all it brings is not having to write sql scripts…