FSharp Record Types With Entity Framework Code-First

馋奶兔 提交于 2019-12-05 00:11:32

问题


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...


回答1:


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.



来源:https://stackoverflow.com/questions/27667902/fsharp-record-types-with-entity-framework-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!