Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FSharp Record Types With Entity Framework Code-First

I am doing a proof of concept in a line of business application where I want to swap out the current C# Code-First Entity Framework implementation with a F# one. I am following this article which seems to work pretty well, but I was hoping to use FSharp record types instead of the classes that the article uses. When I try and add a data annotation to a record type like this:

type Family = {[<Key>]Id:int; LastName:string; IsRegistered:bool}

I get the following error:

Error   1   The type 'Key' is not defined

Is there a way to use data annotations with record types? Apparently, EF Code-First needs annotations...

like image 797
Jamie Dixon Avatar asked Dec 27 '14 13:12

Jamie Dixon


1 Answers

Record types support attributes just fine (and with the syntax you have).

Check if your reference to System.ComponentModel.DataAnnotations is in order, that's where KeyAttribute is defined.

Edit: EF wants to work with properties, that's why using a record doesn't mesh well with EF. You can still make it work in F# 3.0+ by marking the record with CLIMutable attribute (this generates property setters and a parameterless constructor which are taken for granted by C#-centric frameworks and libraries).

The article you're looking at was written with F# 2.0 in mind - CLIMutable wasn't around yet and there was no way of using records for that.

like image 187
scrwtp Avatar answered Nov 15 '22 08:11

scrwtp