Saving F# types to a database

后端 未结 1 779
感动是毒
感动是毒 2021-02-10 09:27

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 persis

相关标签:
1条回答
  • 2021-02-10 10:30

    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.

    0 讨论(0)
提交回复
热议问题