Shortest syntax for POCO compatible with Entity Framework

advertisements

I need F# to work with Entity Framework seemlesly. I am trying to adapt example from here: https://blogs.msdn.microsoft.com/visualstudio/2011/04/04/f-code-first-development-with-entity-framework-4-1/ The problem is that record declaration is so scary there that it is just unacceptable for me.

type public Car() =
    let mutable m_ID : int = 0
    let mutable m_name : string = ""

    [<Key>]
    member public this.ID        with    get()   = m_ID
                                 and     set v   = m_ID <- v
    member public this.Name      with    get()   = m_name
                                 and     set v   = m_name <- v

I have tried CLIMutable in such a way:

module Program    

[<CLIMutable>]
type Car = {
    Name:string
}
let c = new Car(Name = "Honda")

It results in error: "No contructors are available for the type 'Car'". As I understand this answer might be an explanation: https://stackoverflow.com/a/28845368/585819

I also tried things like:

[<CLIMutable>]
type Car =
    {
    ID:int
    } member this.Name = ""

The error is the same. I feel really disappointed. Can somebody help with this?


The CLIMutable attribute does not have any impact on F# use-sites. The added default constructor is inaccessible from F# user-code and so are mutable properties. If you want to use EFs change tracking (from within F#), records are not a good choice (because you can't change it unless you declare all fields mutable). If possible consider using e.g. the SQL Provider. On the other hand e.g. Dapper supports serializing/deserializing POCOs and thusly F# records.

As the record looks immutable from F# perspective, regular construction applies:

let c = { Name = "Honda" }

or (to disambiguate, if you also have e.g. type Person = { Name : string })

let c = { Car.Name = "Honda" }
let c : Car = { Name = "Honda" }
let c = { Name = "Honda" } : Car