A lot of f# articles recommend using fsharp's built in types such as discriminated unions, tuples and records to model the domain. Once we have this model, how can it be persisted to a database?
Entity framework and type providers only work with standard classes with mutable properties.
You can put the [<CLIMutable>]
attribute on records:
[<CLIMutable>]
type Foo = { Bar : string; Baz : int }
This will turn it into a class with mutable properties, when viewed through IL, or from C# or Visual Basic. Viewed from F#, it still looks like an immutable record.
This doesn't really address the problem, though, because there's no corresponding feature for (de)serialising Discriminated Unions.
(As a side remark, IIRC, JSON.net has support for both F# records and discriminated unions, but so far, that's the only exception I'm aware of.)
In my opinion, this is a blessing in disguise, because a Domain Model should be decoupled from persistence details.
In C#, you may think that an ORM like Entity Framework provides such decoupling, but it doesn't. Even with so-called code-first POCO Entities, you still end up creating a relational model, instead of an object-oriented model. Just think of 'navigation properties', which are purely relational concerns. In OOD, such properties violate the law of Demeter (we call them Train Wrecks).
If you want to keep a Domain Model decoupled from implementation details, you'll need to create the model first, and then figure out a way to persist it afterwards. How you do that depends on the persistence technology used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With