将F#类型保存到数据库 [英] Saving F# types to a database

查看:89
本文介绍了将F#类型保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多 f#文章推荐使用fsharp的内置类型,如歧视工会,元组和记录为域建模。一旦我们有了这个模型,它怎么能被持久化到一个数据库呢?



实体框架和类型提供者只能使用具有可变属性的标准类。

解决方案

您可以将 [< CLIMutable>] 属性放在记录上:

 code> [< CLIMutable>] 
type Foo = {Bar:string; Baz:int}

这将会变成一个具有可变属性的类, IL,或从C#或Visual Basic 。从F#看,它仍然是一个不可变的记录。



尽管如此,这并没有真正解决问题,因为(de)序列化歧视联盟没有相应的功能



(作为旁注,IIRC,JSON.net支持F#记录和歧视工会,但到目前为止,这是唯一的例外,我知道。)



在我看来,这是一个伪装的祝福,因为一个域模型应该与持久性细节脱钩



在C#中,您可以认为/ em>像实体框架这样的ORM提供了这样的解耦,但是并没有。即使使用所谓的代码优先的POCO实体,您仍然最终创建一个关系型模型,而不是面向对象的模型。只想到导航属性,这是纯粹的关系问题。在OOD中,这些属性违反了德米特法案(我们称之为火车残骸)。 / p>

如果要保持域模型与实现细节脱钩,您需要先创建模型,然后找出一种方法。这样做取决于使用的持久性技术。


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.

这篇关于将F#类型保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆